1
votes

I have two data frames(df1 and df2)

Let df1 is such a data frame:

col1 col2 col3
a     3    12
a     5    15
b     2    3
a     5    6
a     4    12
b     5    15
a     3    14
c     5    8
c     3    2
c     2    22
b     2    21
a     5    11
b     5    7
c     5    6
a     2    5

Namely `

df1<-data.frame(col1=c("a","a","b","a","a","b","a","c","c","c","b","a","b","c","a") 
                ,col2=c(3,5,2,5,4,5,3,5,3,2,2,5,5,5,2)
                ,col3=c(12,15,3,6,12,15,14,8,2,22,21,11,7,6,5))

Let df2 is such a data frame:

col1  col2 
b     3
c     4

The desired output is:

   col1 col2 col3
a     3    12
b     2    3
a     4    12
b     5    15
a     3    14
c     5    8
c     3    2
c     2    22
b     2    21
b     5    7
c     5    6

Which is a subset of df1. It includes all rows of df1 which eqaual to col1 of df2 or col2 of df2.

For example one of the elements of col1.df2 is "b". So all rows including "b" at col1 of df1 will be element of the desired output.

Also second column of df2 includes "3". So all rows including "3" of at col2 of df1 will be element of the desired output.

And same for "c" and "4".

How can I do that with R? I will be very glad for any help.Thanks a lot.

2
Try df1[df1$col1 %in% df2$col1 | df1$col2 %in% df2$col2,]nicola
@nicola thanks a lot. It works very well.If you click answer and answer there, I will close the subject. Thanks a lot again.oercim
Answered. Glad it helped.nicola

2 Answers

4
votes

Just try:

df1[df1$col1 %in% df2$col1 | df1$col2 %in% df2$col2,]
2
votes

You could also use Reduce with Map if there are many columns

 df1[Reduce(`|`, Map(`%in%`, df1[1:2], df2[1:2])),]