且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

R中==和%in%运算符之间的差异

更新时间:2023-02-06 10:52:24

%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.