How to join multiple data frames using dplyr?

后端 未结 2 1726
陌清茗
陌清茗 2021-01-03 23:04

I want to left_join multiple data frames:

dfs <- list(
  df1 = data.frame(a = 1:3, b = c(\"a\", \"b\", \"c\")),
  df2 = data.frame(c = 4:6, b         


        
相关标签:
2条回答
  • 2021-01-03 23:13

    It's been too late i know....today I got introduced to the unanswered questions section. Sorry to bother.

    Using left_join()

    dfs <- list(
                  df1 = data.frame(b = c("a", "b", "c"), a = 1:3),
                  df2 = data.frame(d = c("a", "c", "d"), c = 4:6),
                  df3 = data.frame(b = c("b", "c", "e"), d = 7:9)
             )
    
    func <- function(...){
      df1 = list(...)[[1]]
      df2 = list(...)[[2]]
      col1 = colnames(df1)[1]
      col2 = colnames(df2)[1]
      xxx = left_join(..., by = setNames(col2,col1))
      return(xxx)
    }
    Reduce( func, dfs)
    #  b a  c  d
    #1 a 1  4 NA
    #2 b 2 NA  7
    #3 c 3  5  8
    

    Using merge() :

    func <- function(...){
      df1 = list(...)[[1]]
      df2 = list(...)[[2]]
      col1 = colnames(df1)[1]
      col2 = colnames(df2)[1]
      xxx=merge(..., by.x = col1, by.y = col2, , all.x = T)
      return(xxx)
    }
    
    Reduce( func, dfs)
    #  b a  c  d
    #1 a 1  4 NA
    #2 b 2 NA  7
    #3 c 3  5  8
    
    0 讨论(0)
  • 2021-01-03 23:14

    Would this work for you?

    jnd.tbl <- df1 %>%
        left_join(df2, by='b') %>%
        left_join(df3, by='d')
    
    0 讨论(0)
提交回复
热议问题