2016-09-11 39 views
2

樣本數據的R - 查找包含所有字符串/圖案所有矢量元素 - str_detect的grep

files.in.path = c("a.4.0. name 2015 - NY.RDS", 
        "b.4.0. name 2016 - CA.RDS", 
        "c.4.0. name 2015 - PA.RDS") 
strings.to.find = c("4.0", "PA") 

欲表示包含所有strings.to.find所有元素的邏輯向量。結果想:

FALSE FALSE TRUE 

此代碼將查找包含strings.to.find中的任何一個元素,即,使用一個或運算

str_detect(files.in.path, str_c(strings.to.find, collapse="|")) # OR operator 
TRUE TRUE TRUE 

此代碼試圖使用AND運算符,但不起作用。

str_detect(files.in.path, str_c(strings.to.find, collapse="&")) # AND operator 
FALSE FALSE FALSE 

這個作品在幾行,我可以寫一個for循環,將生成所有的情況下,各行與strings.to.find

det.1 = str_detect(files.in.path,  "4.0" ) 
det.2 = str_detect(files.in.path,  "PA" ) 
det.all = det.1 & det.2 
FALSE FALSE TRUE 

數量較多,但有一點不更好的辦法涉及使用取決於strings.to.find的位置或順序的正則表達式。

回答

2

一個在網絡上搜索任何「R正則表達式‘和operaror’」「正則表達式‘與運算符’」導致R grep: is there an AND operator?,和Regular Expressions: Is there an AND operator?分別的。

所以同時匹配模式在連接字符串一起

str <- paste0("(?=.*", strings.to.find,")", collapse="") 
grepl(str, files.in.path, perl=TRUE) 

由於霍塔在評論中提及了通過匹配「4.0」,這也將匹配其他蜇傷的時期是一個元字符。一個解決方案是逃避你的模式字符串的時期,即strings.to.find = c("PA", "4\\.0")

+0

@Jota;好點子。例如,'grepl(「4.0」,「4 0」)',所以也許我們可以將其轉義'grepl(「4 \\。0」,「4 0」)' – user2957945

2

這不是繁重,但str_detect被矢量在兩個字符串和模式,這樣你就可以outer功能結合起來得到的東西接近:如果在一個字符串中存在的所有模式

library(stringr) 
outer(files.in.path, strings.to.find, str_detect) 

#  [,1] [,2] 
#[1,] TRUE FALSE 
#[2,] TRUE FALSE 
#[3,] TRUE TRUE 

檢查,apply每所產生的基質連續all邏輯運算符:

apply(outer(files.in.path, strings.to.find, str_detect), 1, all) 

#[1] FALSE FALSE TRUE 

或按@Jota評論,stri_detect_fixed將更加安全,如果方式你是廁所在這裏使用在應完全匹配王:

library(stringi) 
apply(outer(files.in.path, strings.to.find, stri_detect_fixed), 1, all) 
# [1] FALSE FALSE TRUE 
相關問題