words <- c("word1", "word")
text <- c("this is word1", "this is word2", "this is word4")
如果我使用sapply(words, grepl, text)
讓你真假回答的列表, 代替我怎樣讓這個已經匹配了確切的話 使得答案將是
"this is word1"
我對R這個愚蠢的問題是新來的。 歡迎任何想法。
words <- c("word1", "word")
text <- c("this is word1", "this is word2", "this is word4")
如果我使用sapply(words, grepl, text)
讓你真假回答的列表, 代替我怎樣讓這個已經匹配了確切的話 使得答案將是
"this is word1"
我對R這個愚蠢的問題是新來的。 歡迎任何想法。
一種選擇是創建字邊界,然後使用grep
避免串並與value = TRUE
任何部分匹配,它返回的字符串,而不是指數
grep(paste0("\\b(", paste(words, collapse="|"), ")\\b"), text, value = TRUE)
#[1] "this is word1"
可以檢查word =「test」 text = c(「test foo」,「word 1」,「word2」) grep(paste0(「\\ b(」,paste(word,collapse =「| 「),」)\\ b「),text,value = TRUE)。它爲我提供了」test foo「,但不希望它給我沒有答案或null(因爲沒有找到相位)。 – Domnick
@Domnick你的情況對我來說並不明確。如果你想要一個精確的匹配,那麼使用'=='或'%in%'即'哪個(word ==文本)' – akrun
好吧。只是出於好奇才有可能做反之亦然,這意味着如果單詞匹配,從變量*單詞*中得到匹配的單詞? – Domnick
'sapply(也就是說,grep的,文本,值= TRUE)'? – Jaap