如何检查一个向量是否包含给定的值?


当前回答

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

其他回答

检查vector中是否存在元素的另一个选项是使用inops包中的{}%语法中的%,如下所示:

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包于2022-07-16创建(v2.0.1)

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

还要找到元素“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()(返回第一个外观)和%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

你可以使用%in%操作符:

vec <- c(1, 2, 3, 4, 5)
1 %in% vec # true
10 %in% vec # false