Re: [問題] 用一行code str_detect 判斷多個string元素

看板R_Language作者 (天)時間9年前 (2016/11/19 21:09), 編輯推噓2(200)
留言2則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《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

11/20 00:50, , 1F
`==`(length(patterns) 這招真是不錯 推~~
11/20 00:50, 1F

11/20 03:27, , 2F
佩服
11/20 03:27, 2F
文章代碼(AID): #1OC4yERd (R_Language)
文章代碼(AID): #1OC4yERd (R_Language)