如何在R中对数据进行子集而不会丢失NA行?

Rya*_*man 5 r subset dataframe na

我在R中看到了一些数据.一个标题为"Height"的特定列包含几行NA.

我期待我的数据框的子集,以便从我的分析中排除高于某个值的所有高度.

df2 <- subset ( df1 , Height < 40 )
Run Code Online (Sandbox Code Playgroud)

但是,每当我执行此操作时,R会自动删除包含高度NA值的所有行.我不想要这个.我试过为na.rm包含参数

f1 <- function ( x , na.rm = FALSE ) {
df2 <- subset ( x , Height < 40 )
}
f1 ( df1 , na.rm = FALSE )
Run Code Online (Sandbox Code Playgroud)

但这似乎没有做任何事情; NA的行仍然从我的数据框中消失.有没有一种方法可以对我的数据进行子集化,而不会丢失NA行?

李哲源*_*李哲源 13

如果我们决定使用subset功能,那么我们需要注意:

For ordinary vectors, the result is simply ‘x[subset & !is.na(subset)]’.
Run Code Online (Sandbox Code Playgroud)

因此,仅保留非NA值.

如果你想保留NA案例,请使用逻辑或条件告诉R不要丢弃NA案例:

subset(df1, Height < 40 | is.na(Height))
# or `df1[df1$Height < 40 | is.na(df1$Height), ]`
Run Code Online (Sandbox Code Playgroud)

不要直接使用(即将解释):

df2 <- df1[df1$Height < 40, ]
Run Code Online (Sandbox Code Playgroud)

例

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
Run Code Online (Sandbox Code Playgroud)

后者失败的原因是,通过NA给出索引NA.考虑这个带向量的简单示例:

x <- 1:4
ind <- c(NA, TRUE, NA, FALSE)
x[ind]
# [1] NA  2 NA
Run Code Online (Sandbox Code Playgroud)

我们需要以某种方式取代那些NA用TRUE.最直接的方法是添加另一个"或"条件is.na(ind):

x[ind | is.na(ind)]
# [1] 1 2 3
Run Code Online (Sandbox Code Playgroud)

这正是您所处的情况.如果Height包含NA,则逻辑运算Height < 40最终的混合TRUE/ FALSE/ NA,所以我们需要更换NA由TRUE如上.