Home > front end >  Find Partial matching elements between two dataframe columns in r
Find Partial matching elements between two dataframe columns in r

Time:07-11

I have two data frames in which I need to match column A of Input data frame with Lookup data frame and find the partial matching elements. My resulting data frame will be as data frame Result.

A=c("Green|Red|Yellow","Blue","Orange|Peach","Violet")
B=c(23,41,65,89)
Input=data.frame(A,B)

Matches=c("Green","Orange","Red","Yellow","Peach")
Lookup=data.frame(Matches)

Matched=c("Yes","Yes","Yes","No")
Result=data.frame(A,B,Matched)

If someone know the solution pleas help.

CodePudding user response:

We could do it with an ifelsestatement:

library(dplyr)
library(stringr)

Input %>% 
  mutate(Matched = ifelse(str_detect(A, paste(Lookup$Matches, collapse = "|")), "Yes", "No"))
                 A  B Matched
1 Green|Red|Yellow 23     Yes
2             Blue 41      No
3     Orange|Peach 65     Yes
4           Violet 89      No
  • Related