简体   繁体   中英

How to join two data frames by rows based on column value of first data frame in R?

I want to join two data frames like below based on the column value of first data frame :

FIRST DATA FRAME :
a   b   c   d
2   #   #   #
3   #   #   #

SECOND DATA FRAME :
a   b   c   d
1   @   @   @
2   @   @   @
3   @   @   @
4   @   @   @
5   @   @   @

Values of columns other than "a" does not matter. Output should be like :

a   b   c   d
2   #   #   #
3   #   #   #
2   @   @   @
3   @   @   @

I have tried merge, joins of dplyr, intersect etc but could not get correct results.

One way using rbind and intersect . intersect would find out common elements between df1$a and df2$a .

common <- intersect(df1$a, df2$a)
rbind(df1[df1$a %in% common, ], df2[df2$a %in% common, ], make.row.names = F)

#a   b   c   d
#2   #   #   #
#3   #   #   #
#2   @   @   @
#3   @   @   @

I guess one more for variety:

subset(rbind(df1, df2), a %in% a[duplicated(a)])
#  a b c d
#1 2 # # #
#2 3 # # #
#4 2 @ @ @
#5 3 @ @ @

我会尝试用rbind做一些简单的事情

rbind(df1, df2[df2$a %in% df1$a, ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM