【发布时间】:2015-05-09 13:50:45
【问题描述】:
我有一列类型因子。列中的一些值是 NA 值。 如何将所有这些 NA 值转换为新级别,例如 0 或“OriginallyNA”之类的。
我能够将数字类列的 NA 转换为 0,但无法将类因子列转换为 0。
我的数据
> col1 = c(1,2,3,4,NA)
> col2 = c(6,7,NA,NA,8)
> df = data.frame(col1,col2)
> df
col1 col2
1 1 6
2 2 7
3 3 NA
4 4 NA
5 NA 8
> df$col2 = as.factor(df$col2)
> class(df$col1)
[1] "numeric"
> class(df$col2)
[1] "factor"
尝试将 NA 值转换为另一个级别,例如 0
> df[is.na(df)] = 0
Warning message:
In `[<-.factor`(`*tmp*`, thisvar, value = 0) :
invalid factor level, NA generated
> df
col1 col2
1 1 6
2 2 7
3 3 <NA>
4 4 <NA>
5 0 8
> levels(df$col2)
[1] "6" "7" "8"
要不要把factor列转成数值,把NA值改成0,然后转换后转回factor,如下。有没有更好的办法?
> df$col2 = as.numeric(df$col2)
> df
col1 col2
1 1 1
2 2 2
3 3 NA
4 4 NA
5 0 3
> df[is.na(df)] = 0
> df
col1 col2
1 1 1
2 2 2
3 3 0
4 4 0
5 0 3
> df$col2 = as.factor(df$col2)
> df
col1 col2
1 1 1
2 2 2
3 3 0
4 4 0
5 0 3
【问题讨论】:
-
为什么要将数值列转换为因子?接下来将如何处理它?另外,
0是一个有意义的数字,用它代替NA通常是一种不好的做法。 -
不管怎样,我会做类似
df$col2 <- factor(with(df, replace(col2, is.na(col2), 0))) -
您可以尝试
df$col2 <- addNA(df$col2)讨论here -
@PatrickLi,谢谢。您能否将其添加为答案,以便我接受?