R中==和%in%运算符之间的差异 [英] Difference between the == and %in% operators in R

查看:359
本文介绍了R中==和%in%运算符之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题涉及R中==%in%运算符之间的实际区别.

My question concerns the practical difference between the == and %in% operators in R.

我在工作中遇到一个实例,其中使用任一运算符进行过滤会得出不同的结果(例如,一个结果在800行上,另一个在1200行上).我过去曾遇到过此问题,并且能够以确保获得所需结果的方式进行验证.但是,我仍然为它们的不同而感到困惑.

I have run into an instance at work where filtering with either operator gives different results (e.g. one results on 800 rows, and the other 1200). I have run into this problem in the past and am able to validate in a way that ensures I get the results I desire. However, I am still stumped regarding how they are different.

有人可以说明这些运算符的不同之处吗?

Can someone please shed some light on how these operators are different?

推荐答案

%in%值匹配,并且返回其第一个参数在其第二个参数中(第一个)匹配位置的向量(请参见help('%in%'))这意味着您可以比较不同长度的向量,以查看一个向量的元素是否与另一个向量中的至少一个元素匹配.输出的长度将等于要比较的向量的长度(第一个).

%in% is value matching and "returns a vector of the positions of (first) matches of its first argument in its second" (See help('%in%')) This means you could compare vectors of different lengths to see if elements of one vector match at least one element in another. The length of output will be equal to the length of the vector being compared (the first one).

1:2 %in% rep(1:2,5)
#[1] TRUE TRUE

rep(1:2,5) %in% 1:2
#[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

#Note this output is longer in second


==逻辑运算符,用于比较两个事物是否完全相等.如果向量的长度相等,则将对元素进行逐元素比较.否则,载体将被回收.输出的长度将等于较长向量的长度.


== is logical operator meant to compare if two things are exactly equal. If the vectors are of equal length, elements will be compared element-wise. If not, vectors will be recycled. The length of output will be equal to the length of the longer vector.

1:2 == rep(1:2,5)
#[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

rep(1:2,5) == 1:2
#[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE


1:10 %in% 3:7
#[1] FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE

#is same as 

sapply(1:10, function(a) any(a == 3:7))
#[1] FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE


注意:如果可能,请尝试使用identicalall.equal代替==和.


NOTE: If possible, try to use identical or all.equal instead of == and.

这篇关于R中==和%in%运算符之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆