r - returning matched value while using grep -


i using grep function identify if list of string(or col of string) partially present in particular col(query) or not.

test$result <- sapply(test$query,function(x) ifelse(grep(paste(listofstring,collapse="|"),x),1,0)) 

is there way matched string instead of binary output?

for example:

listofstring <- c("mac","windows","linux","android") test <- data.frame(query = c("i love mac","i love ubuntu","i love android","i love both android , linux")) 

using above code able output :

query                               result love mac                            1 love ubuntu                      logical(0) love android                         1 love both android , linux          1 

but want matched value , desired output :

query                              result love mac                          mac love ubuntu                       n/a love android                     android love both android , linux      android love both android , linux       linux 

we can try str_extract

library(stringr) stack(setnames(lapply(str_extract_all(test$query,        paste(listofstring,collapse="|")), function(x)       if(length(x)==0) na else x), test$query))[2:1] #                            ind  values #1                    love mac     mac #2                 love ubuntu    <na> #3                love android android #4 love both android , linux android #5 love both android , linux   linux 

using string in comments

str1 <- "a b c d e f g h" str_match_all(str1, "(?=(a b|b c|c d))")[[1]][,2] #[1] "a b" "b c" "c d" 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -