2016-03-07 43 views
1

比方說,我們有一個單詞列表:可檢查的話從另一個矢量字內出現至少一次

words = c("happy","like","chill") 

現在我有另一個字符串變量:

s = "happyMeal" 

我想檢查單詞中的詞有s中的匹配部分。 所以s可以是「happyTime」,「happyFace」,「happyHour」,但只要在那裏有「開心」,我希望我的結果返回字符串向量單詞中「happy」的索引。

此問題與帖子中提問的問題類似,但不完全相同:Find a string in another string in R

回答

2

可以遍歷每個您正在尋找與sapply的話,使用grepl,以確定該單詞出現在s

sapply(words, grepl, s) 
# happy like chill 
# TRUE FALSE FALSE 

如果s是一個字,然後用sapply回報grepl了可用於確定匹配詞的邏輯矢量:

words[sapply(words, grepl, s)] 
# [1] "happy" 

s包含多個單詞,然後sapplygrepl返回一個邏輯矩陣,則可以使用列總和,以確定哪個單詞出現了至少一次:

s <- c("happyTime", "chilling", "happyFace") 
words[colSums(sapply(words, grepl, s)) > 0] 
# [1] "happy" "chill" 
1

下面是使用stri_detect一個選項從stringi

library(stringi) 
words[stri_detect_regex(s, words)] 
#[1] "happy" 
相關問題