I've a problem to do partial matches from a list of strings to a dataframe.
My df has this structure:
> df
mrun address stat
8988741 cerro pedregal 8536 , Antofagasta, Antofagasta OK
17625851 rancagua 2777 , Iquique, Tarapacá OK
9423953 picarte 4100 , Valdivia, Los Ríos OK
3459140 balmaceda 935 , Temuco, La Araucanía OK
24507700 rancagua 1940, La Serena, Coquimbo OK
> address_list
c("balmaceda", "rancagua", "bombero garrido")
> df_solution
mrun address stat
17625851 rancagua 2777 , Iquique, Tarapacá OK
3459140 balmaceda 935 , Temuco, La Araucanía OK
24507700 rancagua 1940, La Serena, Coquimbo OK
First thing you need to do is to create matching variable in following format:
address_list<- paste(address_list, collapse = ",")
address_list<- gsub("," , "|" , address_list)
address_list<- c("balmaceda|rancagua|bombero|garrido")
Then using grep
you can do a partial matching on your data and create a flag for rows to keep.
# grep(address_list,df$address) Try this and note the output for your understanding of `grep`
df$flag<- NA
df$flag[grep(address_list,df$address)]<- 1 #flag rows with matching values
df_new<- df[which(df$flag==1),]