Lucia Lucia - 2 months ago 11
R Question

matching two lists of words and return the matched words

I want to loop through a list of string to another list

cutter_Ch <- c('happy','birthday','Lucia')
pos <- c('Lucia','today')


one way I can do it is with lapply

pos.matches = lapply(cutter_Ch, pmatch, pos)

[[1]]
[1] NA

[[2]]
[1] NA

[[3]]
[1] 1


However, I want the function return the matched string instead of NA and number of times matched, like this

[[1]]
[1] NA

[[2]]
[1] NA

[[3]]
[1] Lucia

Answer

We need to use the index to subset the 'pos'

lapply(cutter_Ch, function(x) pos[pmatch(x, pos)])

It is not clear whether this example is simplified version of something more complex. Anyway, with str_extract we can get the same output in a vector

library(stringr)
str_extract(cutter_Ch, paste(pos, collapse="|"))
#[1] NA      NA      "Lucia"
Comments