Ryan Oh
Ryan Oh

Reputation: 647

How do I append rows with for loop in R?

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 :)

Upvotes: 0

Views: 192

Answers (1)

Kevin
Kevin

Reputation: 126

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.

Upvotes: 1

Related Questions