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

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -