在R中逐元素比较时如何将NA视为值 [英] How to treat NAs like values when comparing elementwise in R
问题描述
我想逐个比较两个向量,以检查第一个向量中某个位置的元素是否不同于第二个向量中相同位置的元素.
关键是我在向量内有 NA
个值,当对这些值进行比较时,我得到的是 NA
而不是 TRUE
或假
.
I want to compare two vectors elementwise to check whether an element in a certain position in the first vector is different from the element in the same position in the second vector.
The point is that I have NA
values inside the vectors, and when doing the comparison for these values I get NA
instead of TRUE
or FALSE
.
可复制的示例:
这就是我得到的:
a<-c(1, NA, 2, 2, NA)
b<-c(1, 1, 1, NA, NA)
a!=b
[1] FALSE TRUE NA NA NA
这是我希望!=
运算符的工作方式(将 NA
值当作变量的另一个级别"进行处理):
Here is how I would like the !=
operator to work (treat NA
values as if they were just another "level" of the variable):
a!=b
[1] FALSE TRUE TRUE TRUE FALSE
在此链接中,有一个可能的解决方案,但此人正在创建一个函数执行任务.我想知道是否有更优雅的方法来做到这一点.
There's a possible solution at this link, but the guy is creating a function to perform the task. I was wondering if there's a more elegant way to do that.
推荐答案
利用以下事实:
T&NA = NA
但 F&NA = F
和
F |NA = NA
但 T |NA = T
以下解决方案有效,并带有小心放置的括号:
The following solution works, with carefully placed brackets:
(a != b | (is.na(a) & !is.na(b)) | (is.na(b) & !is.na(a))) & !(is.na(a) & is.na(b))
您可以定义:
`%!=na%` <- function(e1, e2) (e1 != e2 | (is.na(e1) & !is.na(e2)) | (is.na(e2) & !is.na(e1))) & !(is.na(e1) & is.na(e2))
然后使用:
a %!=na% b
这篇关于在R中逐元素比较时如何将NA视为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!