如何检查一个向量是否包含给定的值?
当前回答
为此,我非常喜欢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
这些函数区分大小写。
其他回答
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
检查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)
is.element()使代码更具可读性,与%中的%相同
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
为此,我非常喜欢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
这些函数区分大小写。
还要找到元素“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))]