使用多模式字符向量的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个赞
fixed==TRUE
"A1|A9|A6"
.
toMatch <- c("A1", "A9", "A6")
matches <- unique (grep(paste(toMatch,collapse="|"), myfile$Letter, value=TRUE))
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
小怪兽爱吃肉
TA贡献1852条经验 获得超1个赞
#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)}
- 3 回答
- 0 关注
- 508 浏览
添加回答
举报
0/150
提交
取消