I want to replace <NA>
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 comes from a foreign csv file I have to deal with.
df <- data.frame(a=sample(0:10, size=10, replace=TRUE),
b=sample(20:30, size=10, replace=TRUE))
df[df$a==0,'a'] <- NA
df$a <- as.factor(df$a)
Could look like this
a b
1 1 29
2 2 23
3 3 23
4 3 22
5 4 28
6 <NA> 24
7 2 21
8 4 25
9 <NA> 29
10 3 24
Now I want to replace the <NA>
values with a number.
df[is.na(df$a), 'a'] <- 88
In `[<-.factor`(`*tmp*`, iseq, value = c(88, 88)) :
invalid factor level, NA generated
I think I missed a fundamental R concept about factors. Am I?
I can not understand why it doesn't work. I think invalid factor level
means that 88
is not a valid level in that factor, right? So I have to tell the factor column that there is another level?
0
in thedata.frame
call will not be able to replicate your problem, maybe better toset.seed()
. – Jar