I am trying to make a plot function with a set of default values and the flexibility to change these values by using any argument the plot
function accepts inside the dots (...
) argument. An example:
PlotIt <- function(x, y, ...) {
plot(x, y, type = "l", asp = 1, ...)
}
x <- 1:10
y <- 10:1
PlotIt(x = x, y = y)
# Returns a plot
PlotIt(x = x, y = y, asp = NA)
# Error in plot.default(x, y, type = "l", asp = 1, ...) :
# formal argument "asp" matched by multiple actual arguments
The error is naturally because I try to pass the asp argument twice into plot
. So far my best clumsy attempt is to make an if-else statement to take this into account (the approach is modified from here):
PlotIt2 <- function(x, y, ...) {
mc <- match.call(expand.dots = FALSE)
if(names(mc$...) %in% "asp") {
plot(x, y, type = "l", ...)
} else {
plot(x, y, type = "l", asp = 1, ...)
}
}
PlotIt2(x = x, y = y, asp = NA)
# works
To do this for all possible parameters one can set in with the ...
argument, I would need to write a long if-else statement. Is there a more elegant way of doing this?
The question is related to this one with the difference that I want to automatically overwrite all parameters set by the ...
argument.