樣本數據的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
的位置或順序的正則表達式。
@Jota;好點子。例如,'grepl(「4.0」,「4 0」)',所以也許我們可以將其轉義'grepl(「4 \\。0」,「4 0」)' – user2957945