86

How do I join multiple dataframes in R using dplyr ?

new <- left_join(x,y, by = "Flag")

this is the code I am using to left join x and y the code doesn't work for multiple joins

new <- left_join(x,y,z by = "Flag")
2

1 Answer 1

189

You can use a nested left_join

 library(dplyr)
 left_join(x, y, by='Flag') %>%
                left_join(., z, by='Flag') 

Or another option would be to place all the datasets in a list and use merge from base R with Reduce

Reduce(function(...) merge(..., by='Flag', all.x=TRUE), list(x,y,z))

Or we have join_all from plyr. Here we place the dataframes in a list and use the argument type='left' for a left join.

library(plyr)
join_all(list(x,y,z), by='Flag', type='left')

As @JBGruber mentioned in the comments, it can also be done via purrr

library(purrr)
library(dplyr)
purrr::reduce(list(x,y,z), dplyr::left_join, by = 'Flag')
15
  • 10
    I guess you can just embed left_join into Reduce too, but it seems this was already asked a few times yesterday, no? Aug 18, 2015 at 7:47
  • 6
    The pipe option and reduce with join_left are much faster (1.8s) (~10x faster in my case- conditional to your data of course etc..). Reduce with merge is very slow (16s) but if you replace merge with left_join then you have comparable speed as with the pipe (wee bit slower 1.9s on average but not significant). The slowest is join_all from plyr (22s).
    – R. Prost
    Feb 8, 2018 at 7:40
  • 1
    @nouse You could select only the columns that are really needed so that othere than the by columns, there would be unique names in both datasets. If there are duplicate column names, that will append the .x x.x etc.
    – akrun
    Jul 26, 2020 at 19:27
  • 1
    @DannyBullis In tidyverse, the . refers to the entire object from the lhs of %>% So, it is the data.frame created from the left join of x and y
    – akrun
    Jul 5, 2021 at 17:04
  • 1
    Hey @akrun, this is the first hit on Google and it's a great answer. Could you update it to include purrr::reduce since this is, I believe, the best current option purrr::reduce(list(x,y,z), dplyr::left_join, by = 'Flag').
    – JBGruber
    Jan 31, 2022 at 8:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.