Roland
Roland

Reputation: 131

R: How can I append multiple rows to a data.frame during a loop?

I discovered that it seems that I can not add rows to a data.frame in place.

The following code is a minimal example which should append a new row to the data.frame every iteration, but it does not append any.

Please note, in reality I have a complex for-loop with a lot of different if-statements and depending on them I want to append new different data to different data frames.

df <- data.frame(value=numeric()) 

appendRows <- function(n_rows) {
  for(i in 1:n_rows) {
    print(i)
    df <- rbind(df, setNames(i,names(df)))
  }
}
appendRows(10) #Does not append any row, whereas "df <- rbind(df, setNames(1,names(df)))" in a single call appends one row.

How can rows be added to a data.frame in place?

Thanks :-)

Upvotes: 0

Views: 571

Answers (1)

Clemsang
Clemsang

Reputation: 5481

Don't forget to return your object:

df <- data.frame(value=numeric())

appendRows <- function(n_rows) {
  for(i in 1:n_rows) {
    print(i)
    df <- rbind(df, setNames(i,names(df)))
  }
  return(df)
}
appendRows(10) 

To modify df you have to store it:

df <- appendRows(10)

Upvotes: 1

Related Questions