How to perform multiple left joins using dplyr in R

RDplyr

R Problem Overview


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")

R Solutions


Solution 1 - R

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')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpranavView Question on Stackoverflow
Solution 1 - RakrunView Answer on Stackoverflow