0

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.

Bear
  • 662
  • 1
  • 5
  • 20

4 Answers4

0

Try changing c("all", "all", "all") to list("all", "all", "all"). Vectors (created by c()) create columns in dataframes. You can either do list or make the thing you're trying to rbind data.frame (since data.frames are just special lists).

Saurabh Chauhan
  • 3,161
  • 2
  • 19
  • 46
jntrcs
  • 527
  • 1
  • 5
  • 13
0

According to this, the rbind arguments have to be either a data frame or an object that can be coerced into a data frame. It cannot coerce c("All","All","All") into a data frame. I would just create a new data frame instead: d <- rbind(d, data.frame(...)). You may also have some data type mis-matches going on too.

zambonee
  • 1,599
  • 11
  • 17
  • The code `d <- rbind(d, data.frame("All", "All", "All"))` results in `Error in match.names(clabs, names(xi)) : names do not match previous names`. I think it is trying to take this and turn the "All"s into a single column instead of 1 "All" per column from the existing data.frame – Bear Jul 31 '18 at 19:29
  • 1
    Try specifying those data frame column names, eg. `rbind(d, data.frame(some.column="All",some.other.column="All",last.column="All"))`. – zambonee Jul 31 '18 at 19:33
0

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)
Bear
  • 662
  • 1
  • 5
  • 20
0

For one additional way, you can add 1 to the row count of the dataframe and manually insert your values if you choose. It's not the most concise way, but you can mix and match data types.

  # Get the next row number
  row_number <- nrow(df)+1
  
  # Add a new row to a dataframe. You can refer to columns by name 
  # or by column number. 
  df[row_number,"today"] <- lubridate::today()
  df[row_number,"column_2"] <- "My value" 
  df[row_number,3] <- "My next value"
  df[row_number,4] <- "My third value"
Ryan Bradley
  • 627
  • 6
  • 9