如何检查向量是否包含给定值?
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
我将根据输出对选项进行分组 . 假设所有例子都有以下矢量 .
v <- c('z', 'a','b','a','e')
For checking presence:
%in%
> 'a' %in% v [1] TRUE
any()
> any('a'==v) [1] TRUE
is.element()
> is.element('a', v) [1] TRUE
For finding first occurance:
match()
> match('a', v) [1] 2
For finding all occurances as vector of indices:
which()
> which('a' == v) [1] 2 4
For finding all occurances as logical vector :
==
> 'a' == v [1] FALSE TRUE FALSE TRUE FALSE
编辑:从列表中删除 grep() 和 grepl() ,原因在于注释中提到的原因
还要找到元素的位置“哪个”可以用作
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
为此我真的很喜欢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
这些函数区分大小写 .
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
7 回答
any() 函数生成可读代码
我将根据输出对选项进行分组 . 假设所有例子都有以下矢量 .
For checking presence:
%in%
any()
is.element()
For finding first occurance:
match()
For finding all occurances as vector of indices:
which()
For finding all occurances as logical vector :
==
编辑:从列表中删除 grep() 和 grepl() ,原因在于注释中提到的原因
还要找到元素的位置“哪个”可以用作
并找到目标向量中未包含的元素,可以这样做:
match()
(返回第一个外观)和%in%
(返回布尔值)函数都是为此而设计的 .您可以使用
%in%
运算符:为此我真的很喜欢grep()和grepl() .
grep()返回一个整数向量,表示匹配的位置 .
grepl()返回一个逻辑向量,匹配位置为“TRUE” .
这些函数区分大小写 .
is.element()
使代码更易读,并且与%in%
相同