0

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

3

1 Answer 1

1

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