使用多模式字符向量的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 關注
- 551 瀏覽
添加回答
舉報
0/150
提交
取消