match()
(返回第一次出现)和 %in%
(返回布尔值)函数都是为此而设计的。
v <- c('a','b','c','e')
'b' %in% v
## returns TRUE
match('b',v)
## returns the first location of 'b', in this case: 2
is.element()
使代码更具可读性,并且与 %in%
相同
v <- c('a','b','c','e')
is.element('b', v)
'b' %in% v
## both return TRUE
is.element('f', v)
'f' %in% v
## both return FALSE
subv <- c('a', 'f')
subv %in% v
## returns a vector TRUE FALSE
is.element(subv, v)
## returns a vector TRUE FALSE
is.element(x, y) is identical to x %in% y
。但是,我不知道为什么,is.elements
在混合整数和数字时有效,而 %in%
无效
is.element()
与 %in%
的优越可读性是主观的。可以使中缀运算符更具可读性,因为它消除了参数顺序的歧义。 apple in fruit
有道理,fruit in apple
没有。 is.element(apple, fruit)
或 is.element(fruit, apple)
都可能是正确的,具体取决于 is.element
函数的实现。
我将根据输出对选项进行分组。假设所有示例都使用以下向量。
v <- c('z', 'a','b','a','e')
检查存在:
%在%
> 'a' %in% v
[1] TRUE
任何()
> any('a'==v)
[1] TRUE
is.element()
> is.element('a', v)
[1] TRUE
为了找到第一次出现:
匹配()
> match('a', v)
[1] 2
查找所有出现作为索引向量:
哪个()
> which('a' == v)
[1] 2 4
查找所有出现的逻辑向量:
==
> 'a' == v
[1] FALSE TRUE FALSE TRUE FALSE
编辑:出于评论中提到的原因,从列表中删除 grep() 和 grepl()
any() 函数使代码可读
> w <- c(1,2,3)
> any(w==1)
[1] TRUE
> v <- c('a','b','c')
> any(v=='b')
[1] TRUE
> any(v=='f')
[1] FALSE
%in%
的行为不同:any(1==NA)
返回 NA
,其中 1 %in% NA
返回 FALSE
。
any(1==NA, na.rm=TRUE)
返回 FALSE
。
您可以使用 %in%
运算符:
vec <- c(1, 2, 3, 4, 5)
1 %in% vec # true
10 %in% vec # false
还可以找到元素“which”的位置可以用作
pop <- c(3, 4, 5, 7, 13)
which(pop==13)
并找到不包含在目标向量中的元素,可以这样做:
pop <- c(1, 2, 4, 6, 10)
Tset <- c(2, 10, 7) # Target set
pop[which(!(pop%in%Tset))]
match
不同,which
有时实际上更可取,因为它为您提供 all 匹配位置(作为数组)。尽管这可能不是 OP 所要求的,但与 stackoverflow.com/questions/1169388/… 不同
Tset
中的元素,为什么还要使用 which
?您可以直接索引 pop
; pop[!pop%in%Tset]
为此,我非常喜欢 grep() 和 grepl()。
grep() 返回一个整数向量,表示匹配的位置。
yo <- c("a", "a", "b", "b", "c", "c")
grep("b", yo)
[1] 3 4
grepl() 返回一个逻辑向量,在匹配的位置带有“TRUE”。
yo <- c("a", "a", "b", "b", "c", "c")
grepl("b", yo)
[1] FALSE FALSE TRUE TRUE FALSE FALSE
这些函数区分大小写。
grep
将正则表达式作为其第一个元素,因此要对 "b"
进行完全匹配,请使用 ^e$
或添加 , fixed=TRUE
)。
myvar
中,myvar <- 'blah'; grepl('b', myvar, fixed=TRUE)
也会返回 TRUE
。
检查向量中是否存在元素的另一种方法是使用 inops
package 中的 %in{}%
语法,如下所示:
library(inops)
#>
#> Attaching package: 'inops'
#> The following object is masked from 'package:base':
#>
#> <<-
v <- c('a','b','c','e')
v %in{}% c("b")
#> [1] FALSE TRUE FALSE FALSE
由 reprex package (v2.0.1) 于 2022 年 7 月 16 日创建
不定期副业成功案例分享
which(v, 'b')
。注意论点的顺序。which(v, 'b')
给了我一条错误消息:>Error in which(v, 'b') : argument to 'which' is not logical