如果我们决定使用subset
函数,那么我们需要注意:
For ordinary vectors, the result is simply ‘x[subset & !is.na(subset)]’.
因此仅保留非 NA 值。
如果你想保留NA
情况下,使用逻辑或条件告诉 R 不要丢弃NA
cases:
subset(df1, Height < 40 | is.na(Height))
# or `df1[df1$Height < 40 | is.na(df1$Height), ]`
不要直接使用(很快就会解释):
df2 <- df1[df1$Height < 40, ]
Example
df1 <- data.frame(Height = c(NA, 2, 4, NA, 50, 60), y = 1:6)
subset(df1, Height < 40 | is.na(Height))
# Height y
#1 NA 1
#2 2 2
#3 4 3
#4 NA 4
df1[df1$Height < 40, ]
# Height y
#1 NA NA
#2 2 2
#3 4 3
#4 NA NA
后者失败的原因是索引NA
gives NA
。考虑这个带有向量的简单示例:
x <- 1:4
ind <- c(NA, TRUE, NA, FALSE)
x[ind]
# [1] NA 2 NA
我们需要以某种方式取代那些NA
with TRUE
。最直接的方法是添加另一个“或”条件is.na(ind)
:
x[ind | is.na(ind)]
# [1] 1 2 3
这正是您的情况会发生的情况。如果你的Height
包含NA
,然后进行逻辑运算Height < 40
最终混合成TRUE
/ FALSE
/ NA
,所以我们需要替换NA
by TRUE
如上。