Search code examples
rlistleft-joinreducemget

using reduce to left join dataframes which names get from ls()


Using reduce and left_join to combine table_base table_a table_b. Method A can work,but have to input object names , it's little boring. Method B can get object names but can't return correct result ,how to fix it ?Thanks!

library(tidyverse)
table_base <- data.frame(cat=c("a","b","c","d"))

table_a <- data.frame(cat=c("a","b"),
                      value=c(1,2))

table_b <- data.frame(cat=c("a","c","d"),
                      value=c(7,9,10))

# method A: ok, but have to input object name one by one in list

reduce(list(table_base,table_a,table_b),left_join,by='cat') 



# method B: can't work
reduce(list(mget(ls(pattern="^table"))),left_join,by='cat')

Solution

  • Two issues you need to address

    1. mget returns a list already, so you don't need list() to wrap mget any more
    2. The order of dataframes in the list matters, if you want to achieve the same result, you need to adjust the order of dataframes for iterative left_join

    Code (Example only)

    > reduce(mget(ls(pattern = "^table")[c(3, 1, 2)]), left_join, by = "cat")
      cat value.x value.y
    1   a       1       7
    2   b       2      NA
    3   c      NA       9
    4   d      NA      10