作者Edster (Edster)
看板R_Language
標題[問題] 多重選擇的 grep
時間Wed Oct 12 16:39:13 2016
- 問題: 當你想要問問題時,請使用這個類別
[問題類型]:
效能諮詢(我想讓R 跑更快)
[軟體熟悉度]:
請把以下不需要的部份刪除
開發者(有撰寫R 的套件經驗)
[問題敘述]:
一個簡單的問題
一堆字串中,想要擷取/篩選複數條件的字串
例如
"./zw1_agriculture.txt"
"./zw1_agriculture.txt.xml"
"./zw1_bareland.txt"
"./zw1_bareland.txt.xml"
"./zw1_built_up.txt"
"./zw1_built_up.txt.xml"
"./zw1_forest.txt"
"./zw1_forest.txt.xml"
"./zw1_mining.txt"
"./zw1_mining.txt.xml"
"./zw1_watersurface.txt"
"./zw1_watersurface.txt.xml"
等等
只有下面的方法嗎?
for(i in c("mining","watersurface","xml")) f = f[grep(i, f, invert = TRUE)]
我試著用lapply,但最後還需要取交集,不算好用,不如用for.
f = lapply(c("mining","watersurface","xml"),
FUN=function(x){f = f[grep(x, f, invert = TRUE)]; return(f)})
[關鍵字]:
grep, 複選
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.112.64.48
※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1476261555.A.4FB.html
推 clansoda: 是只要達成其中一個就可以嗎? 我之前是用|串起來 10/12 17:02
→ clansoda: 一個OR的概念就可以用一行寫完 10/12 17:03
→ Edster: 歡迎,只要是更簡單的寫法。 10/12 17:09
推 carl090105: 用正則有試過嗎 10/12 19:32
→ Edster: strs[grep(paste(strToFind, collapse = "|"), strs, 10/12 20:41
→ Edster: invert = T)] 10/12 20:42
→ Edster: 感謝提點,原來還有這種做法。 10/12 20:42