0

So let's say I'm trying to make a data frame(df2) that has value of twice as big as another data frame(df1). So the two data frames have exactly the same columns. Also, let's say df1 has 10 objects. Here is my code.

library(data.table)
for (i in (1:10) {
  id <- df1$ID[i]
  newAttr1 <- df1$attr1[i] * 2
  newAttr2 <- df1$attr2[i] * 2
  newAttr3 <- df1$attr3[i] * 2

  NewRow <- list(id, newAttr1, newAttr2, newAttr3)
  rbindlist(list(df2, NewRow))
}

I thought this should work, but somehow there is NO objects in df2. What is the problem?

Thanks a lot in advance :)

4
  • 1
    You don't store the object, use d2<- rbindlist(list(df2, NewRow)) Commented May 7, 2020 at 6:41
  • 1
    Why are you using for loop for this. df1$attr1 * 2 should work directly? Commented May 7, 2020 at 6:53
  • @RonakShah Oh does that do the calculation for ALL objects in the column? Commented May 7, 2020 at 7:25
  • It depends on what you have in attr1 but usually yes. See for example mtcars$mpg * 2. There could be a better way to solve your problem, we might be able to help if you could update with a reproducible example. Commented May 7, 2020 at 7:35

1 Answer 1

1

Maybe this works.

library(data.table)
df2 <- NULL

for (i in (1:10) {
id <- df1$ID[i]
newAttr1 <- df1$attr1[i] * 2
newAttr2 <- df1$attr2[i] * 2
newAttr3 <- df1$attr3[i] * 2

# NewRow <- list(id, newAttr1, newAttr2, newAttr3)
# rbindlist(list(df2, NewRow))

df2 <- rbind(df2, data.frame(id, newAttr1, newAttr2, newAttr3)) 

}

However in this case I think doing it the way Ronak Shah suggests is better.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.