Search code examples
rdataframerbind

Inserting a row into a data.frame in R


I already referenced this question Insert a row in a data.table however, I am getting this error:

Warning message:
In `[<-.factor`(`*tmp*`, ri, value = "All") :
  invalid factor level, NA generated

When I try to insert a new row containing just the value "All" like this:

d <- copy(as.data.frame(Orange))
d <- rbind(d, c("All", "All", "All"))

It gives the warning and inserts "All" into the last 2 columns and inserts NA into the first column.

What am I doing wrong here, I know this should be very simple.


Solution

  • This is the only way I could get this to work without an error. I assume there is a better way to do this though.

    d <- copy(as.data.frame(Orange))
    add <- data.frame("All", "All", "All")
    names(add) <- names(d)
    d <- rbind(d, add)