作者celestialgod (天)
看板R_Language
標題Re: [問題] 用一行code str_detect 判斷多個string元素
時間Sat Nov 19 21:09:30 2016
※ 引述《wanson (望生)》之銘言:
: 我上網看到有人討論
: 當要判斷的strin 為多個可以用
: string =c("a","b")
: str_detect(data, paste(string, collapse = '|'))
: 用| 去判斷字串中有 a or b的出現有無
: 我後來想如果我要取「同時」要有a 與b 本以為只要把| 換成 &
: 可以得到結果
: 但發現似乎沒有相關的討論
: 想要請問一下 是否有更好簡潔的寫法幫助我完成這個需求
迴圈在資料大一點也會慢
會建議下面做法:
library(stringr)
library(pipeR)
strs <- sample(letters[1:4], 500, TRUE) %>>%
(str_c(.[1:125], .[126:250], .[251:375], .[376:500]))
patterns <- letters[1:2]
contain_a_b <- sapply(patterns, str_detect, string = strs) %>>%
rowSums %>>% `==`(length(patterns))
strs[contain_a_b]
--
R資料整理套件系列文:
magrittr #1LhSWhpH (R_Language) https://goo.gl/OBto1x
data.table #1LhW7Tvj (R_Language) https://goo.gl/QFtp17
dplyr(上.下) #1LhpJCfB,#1Lhw8b-s (R_Language) https://goo.gl/GcfNoP
tidyr #1Liqls1R (R_Language) https://goo.gl/pcq5nq
pipeR #1NXESRm5 (R_Language) https://goo.gl/cDIzTh
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.232.189.75
※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1479560974.A.6E7.html
推 cywhale: `==`(length(patterns) 這招真是不錯 推~~ 11/20 00:50
推 wanson: 佩服 11/20 03:27