From time to time I need to allow a user to add optional arguments via ... In some cases these optional arguments are intended for plot()
, and sometimes they are intended for some other function called within my function. I wrote the following function which sorts the arguments into those that go with plot()
and those that don't:
dotsForPlots <- function(..., plot = TRUE) {
dots <- list(...)
dotnames <- names(dots)
dfp <- names(par()) # dfp = dots for plots
# add select args for plot.default
dfp <- c(dfp, "main", "xlim", "ylim", "xlab", "ylab", "type")
if (plot) pass <- which(dotnames %in% dfp)
if (!plot) pass <- which(!dotnames %in% dfp)
return(dots[pass])
}
This works well enough:
tst <- dotsForPlots(cex = 2, noise = 5, junk = "hello",
lty = 3, plot = TRUE, main = "Test Plot")
str(tst)
And here is a function that uses this:
foo <- function(x, y, ...) {
dnp <- dotsForPlots(..., plot = FALSE) # to go to jitter
dnp$x <- y # has to match eventual function call
y <- do.call(jitter, args = dnp)
dfp <- dotsForPlots(...) # to go to plot
dfp$x <- x
dfp$y <- y
do.call(plot, dfp)
}
And running it
foo(x = 1:10, y = 1:10, cex = 2, lty = 2, factor = 10,
main = "Hello", ylab = "", type = "b")
Produces the desired output.
Now the questions:
Is there a built-in way to do this / did I just reinvent the wheel? Seems like there might be but I couldn't find it.
Is there a simpler option in the 2nd function than the
do.call
approach? I'm thinking of something that just allows me to coercedfp
in some way that I can just useplot(x, y, "modified dfp")
so to speak.