Home > Back-end >  Programatically pass a sequence of global variables to a function in r
Programatically pass a sequence of global variables to a function in r

Time:10-25

I have the following:

allPlots <- ggtern::grid.arrange(t1, t2, t3, t4, t5, t6, t7, t8, t9, nrow = 3, ncol = 3)

I want to create a function and pass the variables t1 to t9 programatically instead of manually typing them.

Here is the function:

plotsGrid <- function(...) {
  allPlots <- ggtern::grid.arrange(..., nrow = 3, ncol = 3)
  return (allPlots)
}

Is there a way to pass arguments to a function programatically? (maybe by creating a sequence from t1 to t9 that references global variables)? Any help is appreciated.

CodePudding user response:

Pass a character vector of names and the environment in which to look for them.

f <- function(names = ls(pattern = "^t.$", envir = envir), envir = parent.frame()) {
  do.call(ggtern::grid.arrange, c(mget(names, envir), nrow = 3, ncol = 3))
}

# test
library(ggplot2)
t1 <- t2 <- ggplot(iris, aes(Sepal.Width, Sepal.Length))   geom_line()  
f()

CodePudding user response:


# create some dummy data
df <- data.frame()
t1 <- qplot(1:10, rnorm(10))
t2 <- t1
t4 <- t1
t5 <- t1
t6 <- t1
t7 <- t1

plotsGrid <- function(pattern, title = '', nc = 3) {
  vars <- ls(pattern = pattern, envir = .GlobalEnv)
  nr <- ceiling(length(vars) / 3)
  var_str <- paste0(vars, collapse = ', ')
  code_str <- sprintf('gridExtra::grid.arrange(%s, nrow = %s, ncol = %s, top = \'%s\')', 
                      var_str, 
                      nr, 
                      nc, 
                      title)
  message(code_str)
  allPlots <- parse(text = code_str) |> 
    eval()
  return (allPlots)
}

plotsGrid('t[0-9] ')|> print()
  •  Tags:  
  • r
  • Related