亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用多模式字符向量的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 關注
  • 551 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號