I want to replace
values in a factors column with a valid value. But I can not find a way. This example is only for demonstration. The original data
The problem is that NA
is not a level of that factor:
> levels(df$a)
[1] "2" "4" "5" "9" "10"
You can't change it straight away, but the following will do the trick:
df$a <- as.numeric(as.character(df$a))
df[is.na(df$a),1] <- 88
df$a <- as.factor(df$a)
> df$a
[1] 9 88 3 9 5 9 88 8 3 9
Levels: 3 5 8 9 88
> levels(df$a)
[1] "3" "5" "8" "9" "88"