0

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.

SevenSouls
  • 539
  • 3
  • 12

2 Answers2

3

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()
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
1

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

t1 <- t2 <- t3 <- t4 <- t5 <- t6 <- ggplot2::qplot(1:10, rnorm(10))
plotsGrid('t[0-9]+')|> print()
br00t
  • 1,440
  • 8
  • 10
  • 2
    why convert your code to a string just to use [`eval + parse`](https://stackoverflow.com/questions/13649979/what-specifically-are-the-dangers-of-evalparse#:~:text=The%20use%20of%20eval%20%28%29%20can%20also%20cause,resort%20to%20eval%20%28%29%20Share%20Improve%20this%20answer)? Note that this method is not recommended – Onyambu Oct 24 '22 at 23:57