Drashti
Drashti

Reputation: 105

Merging 2 dataframes by common column values under a common column name in R

I want to merge two data frames that have the same column name and some similar values. I.e

         Dataframe 1                                  Dataframe 2
    ID    COLOUR   FRUIT                        ID    SHAPE   STATUS 
    A     Yellow   Apple                        A     Circle   On
    B     Blue     Banana                       B     Square   On
    C     Purple   Apple                        D     Triangle Off
    D     Orange   Grapes                           

I want to 1) compare the IDs of these two datagrams and keep the ones that occur in both data frames and remove the ones that don't overlap. 2) Combine the two data frames using the common values of the ID column. I tried to make the ID column into rownames, but since some of the IDs are duplicated in each of these data frames, I was unable to do that.

Any help is appreciated.

Thank you in advance!

Upvotes: 1

Views: 1497

Answers (2)

Sweepy Dodo
Sweepy Dodo

Reputation: 1873

library(data.table)

# set as data.table
lapply(list(df1, df2), \(i) setDT(i))

# inner join
df1[df2, on=.(ID), nomatch=0]

Upvotes: 3

GuedesBF
GuedesBF

Reputation: 9878

We are looking for a inner join here:

library(dplyr)

inner_join(`Dataframe 1`, `Datadrame 2`, by = 'ID')

Upvotes: 2

Related Questions