I want to change a single value in a data.frame, which is NA using this code df[307, 1] <- 231
. However, I get the warning message
warning message:
In `[<-.factor`(`*tmp*`, iseq, value = 231) :
invalid factor level, NA generated
As I understood right, the level 231
is not within the levels of the variable ([,1]
first column). What can I do to solve this problem? Add new level 231
? Or another way to change this single value. Thanks for your ideas.
As @akrun noted in the comments:
x <- factor(c("a", "b"))
x[3] <- "c"
Warning message:
In `[<-.factor`(`*tmp*`, 3, value = "c") :
invalid factor level, NA generated
# one solution:
x <- factor(c("a", "b"))
x <- factor(c(as.character(x), "c"))
# a second solution:
x <- factor(c("a", "b"))
levels(x) <- c("a", "b", "c")
x[3] <- "c"