0
votes

I would like to use ... to pass arguments into ggplot in a different function. For example:

dat <- data.frame(x = c(1, 2, 3), y = c(1, 2, 3))

f <- function(dat) { 
  ylimits = c(min(dat$x, dat$y), max(dat$x, dat$y))

  g(dat, ylim = ylimits)
}

g <- function(dat, ...) {
 args <- eval(substitute(alist(...)))

 ggplot(dat, aes(x = x, y = y)) + geom_point() + coord_cartesian(ylim = args[['ylim']])
}

f(dat)

I tried using eval(args[['ylim']]), various combinations of quote/deparse/substitute but I haven't been able to get it to evaluate properly.

1
Why not just args <- list(...)? That works for me. - BrodieG
google 'R ellipsis' - Marat Talipov

1 Answers

0
votes

The environment of the previous function isn't passed along with the object, so if you save the call and then try to evaluate it the expression in g it won't be able to find ylimits, which only exists in f's environment.

One option is to use the lazyeval package, but it is currently being deprecated in favor of rlang, whose dots_list will do the trick nicely for you:

library(ggplot2)

dat <- data.frame(x = c(1, 2, 3), y = c(1, 2, 3))

f <- function(dat) { 
    ylimits = c(min(dat$x, dat$y), max(dat$x, dat$y))

    g(dat, ylim = ylimits)
}

g <- function(dat, ...) {
    args <- rlang::dots_list(...)

    ggplot(dat, aes(x = x, y = y)) + geom_point() + coord_cartesian(ylim = eval(args[['ylim']]))
}

f(dat)