我有一个名为 SMOKE 的因子,级别为“Y”和“N”。缺失值被替换为 NA(从初始级别“NULL”开始)。然而,当我查看这个因素时,我得到这样的结果:
head(SMOKE)
# N N <NA> Y Y N
# Levels: Y N
为什么 R 显示 NA
如<NA>
?有什么区别吗?
最佳答案
当您处理factors
时,当 NA
包含在尖括号 ( <NA>
) 中,这表明它实际上是 NA。
什么时候NA
如果没有括号,那么它不是 NA,而是一个标签为 "NA"
的真因数。
# Note a 'real' NA and a string with the word "NA"
x <- factor(c("hello", NA, "world", "NA"))
x
[1] hello <NA> world NA
Levels: hello NA world <~~ The string appears as a level, the actual NA does not.
as.numeric(x)
[1] 1 NA 3 2 <~~ The string has a numeric value (here, 2, alphabetically)
The NA's numeric value is just NA
<小时/>
编辑回答@Arun的问题:
R
只是试图区分值为两个字母 "NA"
的字符串和实际缺失值 NA
因此,您在显示 df
时看到的差异与 df$y
。示例:
df <- data.frame(x=1:4, y=c("a", NA_character_, "c", "NA"), stringsAsFactors=FALSE)
注意 NA 的两种不同风格:
> df
x y
1 1 a
2 2 <NA>
3 3 c
4 4 NA
但是,如果我们只看“df$y”
[1] "a" NA "c" "NA"
但是,如果我们删除引号(类似于我们在控制台打印 data.frame 时看到的内容):
print(df$y, quote=FALSE)
[1] a <NA> c NA
因此,我们再次区分 NA
通过尖括号。
关于r - <NA> 和 NA 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16253789/