是否有相当于==但结果x != NA如果x不是NA?
以下是我想要的,但它很笨重:
mapply(identical, vec1, vec2)
Run Code Online (Sandbox Code Playgroud)
mis*_*raP 10
只需用%in%替换“ ==”。
例:
> df <- data.frame(col1= c("a", "b", NA), col2= 1:3)
> df
col1 col2
1 a 1
2 b 2
3 <NA> 3
> df[df$col1=="a", ]
col1 col2
1 a 1
NA <NA> NA
> df[df$col1%in%"a", ]
col1 col2
1 a 1
> "x"==NA
[1] NA
> "x"%in%NA
[1] FALSE
Run Code Online (Sandbox Code Playgroud)
1 == NA返回逻辑NA而不是TRUE或FALSE.如果你想打电话NA FALSE,你可以添加第二个条件:
set.seed(1)
x <- 1:10
x[4] <- NA
y <- sample(1:10, 10)
x <= y
# [1] TRUE TRUE TRUE NA FALSE TRUE TRUE FALSE TRUE FALSE
x <= y & !is.na(x)
# [1] TRUE TRUE TRUE FALSE FALSE TRUE TRUE FALSE TRUE FALSE
Run Code Online (Sandbox Code Playgroud)
您还可以使用第二个处理步骤将NA等同测试中的所有值转换为FALSE.
foo <- x <= y
foo[is.na(foo)] <- FALSE
foo
# [1] TRUE TRUE TRUE FALSE FALSE TRUE TRUE FALSE TRUE FALSE
Run Code Online (Sandbox Code Playgroud)
而且,为了它的价值,NA == NA回报NA也是如此NA != NA.