过滤器/子集空单元格“”与 NA。为什么 subset (df, x =='') 不是 subset(df, x !='') 的反义词。 dplyr 或 base 中的错误?
filter / subset empty cells "" vs. NA. Why is subset (df, x =='') not the opposite of subset(df, x !=''). Bug in dplyr or base?
考虑一个您要过滤的简单数据框:
df <- data.frame(x = c('', '', NA, NA ))
> df
x
1
2
3 <NA>
4 <NA>
正如预期的那样 subset(df, x =='')
结果:
x
1
2
然而,令我非常惊讶的是 subset(df, x !='')
结果:
[1] x
<0 rows> (or 0-length row.names)
谁能解释为什么 ''
在与 ==
一起使用时排除 NA
,但在与 !=
一起使用时却包括 NA
。除了 R 基本函数中的错误之外,还有什么别的吗?同样适用于 dplyr
filter()
:
library(dplyr)
df%>%filter(x !='')
df%>%filter(x =='')
我们可以使用 is.na
的条件
subset(df, is.na(x) | x != "")
因为 ==
或 !=
returns NA
NA
元素(即与 NA
returns 的任何比较NA) 存在并且不是逻辑向量。 subset
和 filter
删除那些 NA
行,如 ?subset
的文档中所示
subset - logical expression indicating elements or rows to keep: missing values are taken as false
并在 ?filter
Note that when a condition evaluates to NA the row will be dropped, unlike base subsetting with [.
即
with(df, x != "")
#[1] FALSE FALSE NA NA
with(df, is.na(x) | x != "")
#[1] FALSE FALSE TRUE TRUE
考虑一个您要过滤的简单数据框:
df <- data.frame(x = c('', '', NA, NA ))
> df
x
1
2
3 <NA>
4 <NA>
正如预期的那样 subset(df, x =='')
结果:
x
1
2
然而,令我非常惊讶的是 subset(df, x !='')
结果:
[1] x
<0 rows> (or 0-length row.names)
谁能解释为什么 ''
在与 ==
一起使用时排除 NA
,但在与 !=
一起使用时却包括 NA
。除了 R 基本函数中的错误之外,还有什么别的吗?同样适用于 dplyr
filter()
:
library(dplyr)
df%>%filter(x !='')
df%>%filter(x =='')
我们可以使用 is.na
subset(df, is.na(x) | x != "")
因为 ==
或 !=
returns NA
NA
元素(即与 NA
returns 的任何比较NA) 存在并且不是逻辑向量。 subset
和 filter
删除那些 NA
行,如 ?subset
subset - logical expression indicating elements or rows to keep: missing values are taken as false
并在 ?filter
Note that when a condition evaluates to NA the row will be dropped, unlike base subsetting with [.
即
with(df, x != "")
#[1] FALSE FALSE NA NA
with(df, is.na(x) | x != "")
#[1] FALSE FALSE TRUE TRUE