如果在给定字符向量中的任何位置找到模式grep,R中是否有一个函数返回?TRUEFALSE
我看到的所有函数都返回了找到的每个元素的当前位置的向量.
say*_*y69 25
可能是grepl()和any()?的组合?
喜欢
> foo = c("hello", "world", "youve", "got", "mail")
> any(grepl("world", foo))
[1] TRUE
> any(grepl("hi", foo))
[1] FALSE
> any(grepl("hel", foo))
[1] TRUE
Run Code Online (Sandbox Code Playgroud)
你的问题有点不清楚,你是否希望最后一个例子返回真实
Jef*_*len 24
也许你在寻找grepl()?
> grepl("is", c("This", "is", "a", "test", "isn't", "it?"))
[1] TRUE TRUE FALSE FALSE TRUE FALSE
Run Code Online (Sandbox Code Playgroud)
如果第一个参数是您要查找的模式,则第二个参数是您要匹配的向量,返回的值是一个相同长度的布尔向量,用于描述模式是否与每个元素匹配.
Arc*_*mag 14
你在寻找"任何"吗?
> x<-c(1,2,3,4,5)
> x==5
[1] FALSE FALSE FALSE FALSE TRUE
> any(x==5)
[1] TRUE
Run Code Online (Sandbox Code Playgroud)
请注意,您也可以为字符串执行此操作
> x<-c("a","b","c","d")
> any(x=="b")
[1] TRUE
> any(x=="e")
[1] FALSE
Run Code Online (Sandbox Code Playgroud)
结合使用时可以很方便:
> sapply(c(2,4,6,8,10), function(x){ x%%2==0 } )
[1] TRUE TRUE TRUE TRUE TRUE
> any(sapply(c(2,4,6,8,10), function(x){ x%%2!=0 } ))
[1] FALSE
Run Code Online (Sandbox Code Playgroud)
grepl 就是你要找的
grepl("is", "This is grepl test")
[1] TRUE
grepl("is not", "This is grepl test")
[1] FALSE
Run Code Online (Sandbox Code Playgroud)