将NA转换为因子水平 [英] Convert NA into a factor level
问题描述
我有一个具有NA
值的向量,我想用一个新的因子水平NA
代替.
I have a vector with NA
values that I would like to replace by a new factor level NA
.
a = as.factor(as.character(c(1, 1, 2, 2, 3, NA)))
a
[1] 1 1 2 2 3 <NA>
Levels: 1 2 3
这有效,但似乎是一种奇怪的方法.
This works, but it seems like a strange way to do it.
a = as.factor(ifelse(is.na(a), "NA", a))
class(a)
[1] "factor"
这是预期的输出:
a
[1] 1 1 2 2 3 NA
Levels: 1 2 3 NA
推荐答案
您可以使用addNA()
.
x <- c(1, 1, 2, 2, 3, NA)
addNA(x)
# [1] 1 1 2 2 3 <NA>
# Levels: 1 2 3 <NA>
这基本上是使用exclude = NULL
分解的便捷功能.来自help(factor)
-
This is basically a convenience function for factoring with exclude = NULL
. From help(factor)
-
addNA
通过将NA
转换为额外级别来修改因子(例如,NA
值在表中进行计数).
addNA
modifies a factor by turningNA
into an extra level (so thatNA
values are counted in tables, for instance).
所以这很好的另一个原因是,如果您已经具有因子f
,则可以使用addNA()
快速将NA
作为因子级别添加而无需更改f
.如文档中所述,这对于表很方便.它也很好看.
So another reason this is nice is because if you already have a factor f
, you can use addNA()
to quickly add NA
as a factor level without changing f
. As mentioned in the documentation, this is handy for tables. It also reads nicely.
这篇关于将NA转换为因子水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!