1
votes

Beginner here.

I'm trying to append a row to an existing data frame. I made a new vector (below) and then tried to bind it to the original data frame. Received some warning messages.

#append new row
new_row <- c(50, 22, "Roberto", "Bolano", "MALE", "2003-07-15")

#bind to original data frame
writers_df_large <- rbind(writers_df, new_row)

Warning messages: 1: In [<-.factor(*tmp*, ri, value = "Roberto") : invalid factor level, NA generated

2: In [<-.factor(*tmp*, ri, value = "Bolano") : invalid factor level, NA generated

3: In [<-.factor(*tmp*, ri, value = "2003-07-15") : invalid factor level, NA generated

StringsAsFactors = FALSE should solve this, but I'm not sure how to go about it.

1
Another way, is to convert your vector to a data.frame, assign it the same names as your data, then rbind will work, with factor levels extended. - user20650

1 Answers

4
votes

You'll probably be less stressed out working with characters at first, then ease yourself into factors later (they can be quite frustrating). So first, coerce all the factor columns to character with

writers_df_large[] <- lapply(writers_df_large, function(x) {
    if(is.factor(x)) as.character(x) else x
})

or

v <- vapply(writers_df_large, is.factor, NA)
writers_df_large[v] <- lapply(writers_df_large[v], as.character)

Secondly, use a list for the new row because with c() you will coerce all the values to character.

new_row <- list(50, 22, "Roberto", "Bolano", "MALE", "2003-07-15")

Now you can add the new row with rbind()

rbind(writers_df_large, new_row)