R exact and partial match in multiple columns

Experts at R.

I have two data frames.

dataframe one:

df1 <- c("xx", "bb", "zz")

dataframe two:

df2 <- data.frame(A=c("xx", "be", "zz", "jj"), B=c("xyx, uu, zz", "uu, zbbz, zbz, ccc", "cc, zzx", "ddd"), C=c("bbbb", "yyy", "xxq", "ooo"), D=c("ooo", "yyy", "ccc", "zoz"))

So df2 looks like this:

   A                  B    C   D
1 xx        xyx, uu, zz bbbb ooo
2 be uu, zbbz, zbz, ccc  yyy yyy
3 zz            cc, zzx  xxq ccc
4 jj                ddd  ooo zoz

I want to map x to y to get a new data frame. Looking at the answers of Stackoverflow, I learned how to make an exact comparison. However, in the current situation, I want to perform an exact match and a partial match. It seems to me that "grep" can help, but I can not get it to work for my business, please kindly help.

In df1, I have three words for matching "xx", "bb" and "zz". Instead of looking for exact xx, bb, zz in df2. I want to check if these terms can be found in columns A and B of df2, which may contain exact match and partial match.

For example, I would consider

  • xx 1 ( A1)

  • bb 2 ( B2)

  • zz 1 3 ( B1 A3, B3 ),

  • zz , , 3, , 1 .

  • 4 df2 , .

, dataframe, df2 df1 :

  V1   A                  B    C   D
1 xx   xx        xyx, uu, zz bbbb ooo
2 bb   be uu, zbbz, zbz, ccc  yyy yyy
3 zz   zz            cc, zzx  xxq ccc
4 zz   xx        xyx, uu, zz bbbb ooo

grep sort ? . .

+3
1

:

dfrPerVal<-lapply(df1, function(dfrPartFor){
        whereFoundA<-grep(dfrPartFor, df2$A, fixed=TRUE)
        whereFoundB<-grep(dfrPartFor, df2$B, fixed=TRUE)
        retval<-cbind(1=dfrPartFor, df[union(whereFoundA, whereFoundB),]
        xmatch<-which((retval$A==dfrPartFor) | (retval$B==dfrPartFor))
        if(length(xmatch) > 0)
        {
            retval<-rbind(retval[xmatch, ], retval[-xmatch, ])
        }
        return(retval)
    })
finalResult<-do.call(rbind, dfrPerVal)

, ...

+2