本文介绍了将NA转换为因子水平的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有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) -

所以这很好的另一个原因是,如果您已经具有因子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转换为因子水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 05:25
查看更多