为了账号安全,请及时绑定邮箱和手机立即绑定

使用多模式字符向量的grep

使用多模式字符向量的grep

侃侃无极 2019-07-04 13:50:58
使用多模式字符向量的grep我试着用grep测试字符串向量是否存在于另一个向量中,并输出存在的值(匹配模式)。我有这样一个数据框架:FirstName Letter    Alex      A1 Alex      A6 Alex      A7 Bob       A1 Chris     A9 Chris     A6我在“信函”列中找到字符串模式的向量,例如:c("A1", "A9", "A6").我想检查模式向量中的任何字符串是否存在于“信函”列中。如果是的话,我想要的是唯一值的输出。问题是,我不知道怎么用grep有多种模式。我试过:matches <- unique (     grep("A1| A9 | A6", myfile$Letter, value=TRUE, fixed=TRUE))但是它给了我0场比赛,这不是真的,有什么建议吗?
查看完整描述

3 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

除了@Marek关于不包括fixed==TRUE,您还需要在正则表达式中不包含空格。应该是"A1|A9|A6".

你还提到有很多模式。假设它们在向量中

toMatch <- c("A1", "A9", "A6")

然后,您可以直接从这里创建正则表达式。

matches <- unique (grep(paste(toMatch,collapse="|"), 
                        myfile$Letter, value=TRUE))


查看完整回答
反对 回复 2019-07-04
?
holdtom

TA贡献1805条经验 获得超10个赞

好的答案,但是不要忘记filter()来自Dplyr:


patterns <- c("A1", "A9", "A6")

>your_df

  FirstName Letter

1      Alex     A1

2      Alex     A6

3      Alex     A7

4       Bob     A1

5     Chris     A9

6     Chris     A6


result <- filter(your_df, grepl(paste(patterns, collapse="|"), Letter))


>result

  FirstName Letter

1      Alex     A1

2      Alex     A6

3       Bob     A1

4     Chris     A9

5     Chris     A6


查看完整回答
反对 回复 2019-07-04
?
小怪兽爱吃肉

TA贡献1852条经验 获得超1个赞

根据Brian Digg的文章,以下是筛选列表的两个有用函数:

#Returns all items in a list that are not contained in toMatch#toMatch can be a single item or a list of itemsexclude
 <- function (theList, toMatch){
  return(setdiff(theList,include(theList,toMatch)))}#Returns all items in a list that ARE contained in toMatch#toMatch can be
   a single item or a list of itemsinclude <- function (theList, toMatch){
  matches <- unique (grep(paste(toMatch,collapse="|"), 
                          theList, value=TRUE))
  return(matches)}


查看完整回答
反对 回复 2019-07-04
  • 3 回答
  • 0 关注
  • 473 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信