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")
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')
left_join
into Reduce
too, but it seems this was already asked a few times yesterday, no?
Aug 18, 2015 at 7:47
by
columns, there would be unique names in both datasets. If there are duplicate column names, that will append the .x
x.x
etc.
.
refers to the entire object from the lhs of %>%
So, it is the data.frame created from the left join of x and y
purrr::reduce
since this is, I believe, the best current option purrr::reduce(list(x,y,z), dplyr::left_join, by = 'Flag')
.
left_join
instead ofmerge
if you like.Reduce(function(dtf1,dtf2) left_join(dtf1,dtf2,by="index"), list(x,y,z))
. Since this question is marked as duplicate, I gave a detailed answer with example on the question Simultaneously merge multiple data.frames in a list.