r - Check which words show up at least once within words from another vector -
let's have list of words:
words = c("happy","like","chill")
now have string variable:
s = "happymeal"
i wanted check word in words has matching part in s. s "happytime", "happyface", "happyhour", long there's "happy" in there, want result return index of word "happy" in string vector words.
this question similar not identical question asked in post: find string in string in r.
you can loop through each of words you're searching sapply
, using grepl
determine if word appears in s
:
sapply(words, grepl, s) # happy chill # true false false
if s
single word sapply
grepl
returns logical vector can use determine words matched:
words[sapply(words, grepl, s)] # [1] "happy"
when s
contains multiple words, sapply
grepl
returns logical matrix, , can use column sums determine words showed @ least once:
s <- c("happytime", "chilling", "happyface") words[colsums(sapply(words, grepl, s)) > 0] # [1] "happy" "chill"
Comments
Post a Comment