Reputation: 6094
here's a minimal reproducible example of what i want to happen
myfun <-
function( ... ){
# myfun only passes `...` on to the plot function
plot(
... ,
if( !'xlab' %in% names( list( ... ) ) ) xlab = 'mylabel' ,
if( !'ylab' %in% names( list( ... ) ) ) ylab = 'ylabel'
)
}
# works the way i want: user specified `xlab` and `ylab` so `...` used them
myfun( 1 , 1 , xlab = "new label" , ylab = "another label" )
# fails
myfun( 1 , 1 )
# Error in plot.window(...) : invalid 'xlim' value
since the user did not specify xlab
and ylab
, i wanted my function to use the defaults that i have set. so
plot( 1 , 1 , xlab = 'mylabel' , ylab = 'ylabel' )
what's the smartest way to do this if i have many possibilities like xlab
and ylab
? i might want add defaults for title=
and xlim=
and ylim=
as well, so writing out every combination is not feasible? thanks!!
Upvotes: 2
Views: 88
Reputation: 15708
Solution 1
Make your own custom wrapper to the plot
function:
myplot <- function(x, y, xlab = 'mylabel', ylab = 'ylabel', ...){
plot(x, y, xlab = xlab, ylab = ylab, ...)
}
myfun <-
function( ... ){
# myfun only passes `...` on to the plot function
myplot(...)
}
Now the following calls work as I think you want them to work:
myfun(1, 1)
myfun(1, 1,xlab = "new label" , ylab = "another label" )
Solution 2
You can also use list(...)
and do.call
in the following manner:
myfun <-
function( ... ){
dots = list(...)
# check whether needed defaults are supplied, if not, supply them.
if ~grep('xlab', names(dots) ){
dots$xlab = 'mylabel'
}
if ~grep('ylab', names(dots) ){
dots$ylab = 'ylabel'
}
# myfun only passes `...` on to the plot function
do.call(plot, dots)
}
Upvotes: 2