By Roland


2020-01-14 12:48:03 8 Comments

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

1 comments

@Clemsang 2020-01-14 13:19:38

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)

Related Questions

Sponsored Content

19 Answered Questions

[SOLVED] How to rename a single column in a data.frame?

  • 2011-09-23 16:08:34
  • screechOwl
  • 869606 View
  • 335 Score
  • 19 Answer
  • Tags:   r

16 Answered Questions

[SOLVED] Remove rows with all or some NAs (missing values) in data.frame

19 Answered Questions

[SOLVED] How to sort a dataframe by multiple column(s)

2 Answered Questions

[SOLVED] Splitting a data.frame By Column Patterns and Binding Rows R

2 Answered Questions

1 Answered Questions

[SOLVED] How to apply findAssoc against each row of data.frame

  • 2015-12-14 14:44:02
  • DirkLX
  • 207 View
  • 0 Score
  • 1 Answer
  • Tags:   r dataframe tm

1 Answered Questions

[SOLVED] Define header fields for variables in rbind

  • 2014-10-21 17:20:53
  • viridius
  • 740 View
  • 0 Score
  • 1 Answer
  • Tags:   r rbind

2 Answered Questions

[SOLVED] How to score a data.frame based on another data.frame?

  • 2014-04-16 15:57:19
  • Micro
  • 79 View
  • 0 Score
  • 2 Answer
  • Tags:   r

Sponsored Content