2

I wish to create a user function in R which merges multiple tables that uses regular expression to find these tables. In my situation, I want to merge all the tables in my environment starting with "m_".

This produces exactly what I want:

Reduce(function(...) merge(..., all = TRUE), mget(apropos("^m_")))

But it doesn't work when I attempt to transform this code into a user function:

    multi.merge <- function(...){
        x <- Reduce(function(...) merge(..., all = TRUE), mget(apropos(...))
        return(x)
}

dt <- multi.merge("^m_")

Error: value for ‘m_table1’ not found

I have tried using different functions such as get0 or syms, and different syntax just ends up with the same error. I suspect it's just something to do with a problem in the structure of the function that I don't understand.

Is there any way to make this work?

L77
  • 137
  • 7

2 Answers2

2

Try sending a fixed argument in the function.

multi.merge <- function(pattern){
   Reduce(function(...) merge(..., all = TRUE), mget(ls(pattern = pattern))
   #Or
   #Reduce(function(...) merge(..., all = TRUE), mget(apropos(pattern))
}


dt <- multi.merge("^m_")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

We can use reduce will full_join

library(dplyr)
library(purrr)
multi.merge <- function(pattern) {
        mget(ls(pattern = pattern, envir = .GlobalEnv), envir = .GlobalEnv)  %>%
              reduce(full_join)
  }

dt <- multi.merge("^m_")

data

m_table1 <- structure(list(col1 = 1:5), class = "data.frame", row.names = c(NA, 
-5L))

m_table2 <- structure(list(col1 = 2:7, value = c(0.620061606036922, -0.833792752750578, 
-0.939990781455841, 0.00275725433910228, 1.40140753383493, 0.708695548097395
)), class = "data.frame", row.names = c(NA, -6L))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • This returns: **Error: `.x` is empty, and no `.init` supplied** Could there be something wrong with my regular expression pattern? I have tables such as "m_table1", "m_table2" that I am trying to match. This should be correct? @akrun – L77 Jan 30 '20 at 22:21
  • Can you try `multi.merge("^m_table\\d+$")` – akrun Sep 18 '20 at 19:10