如何 grep 向量并返回单个 TRUE 或 FALSE? [英] How to grep a vector and return a single TRUE or FALSE?

查看:53
本文介绍了如何 grep 向量并返回单个 TRUE 或 FALSE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R 中是否有 grep 函数,如果在给定字符向量中的任何位置找到模式,则返回 TRUE,否则返回 FALSE?

Is there a grep function in R that returns TRUE if a pattern is found anywhere in the given character vector and FALSE otherwise?

我看到的所有函数都返回一个向量,表示找到的每个元素的当前位置.

All the functions I see return a vector of the current positions of each element found.

推荐答案

您在寻找任何"吗?

> x<-c(1,2,3,4,5)
> x==5
[1] FALSE FALSE FALSE FALSE  TRUE
> any(x==5)
[1] TRUE

请注意,您也可以对字符串执行此操作

Note that you can do this for strings as well

> x<-c("a","b","c","d")
> any(x=="b")
[1] TRUE
> any(x=="e")
[1] FALSE

与apply结合使用会很方便:

And it can be convenient when combined with applies:

> 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

这篇关于如何 grep 向量并返回单个 TRUE 或 FALSE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆