Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple ellipses arguments in R

Tags:

r

Is it possible to have multiple ellipsis arguments in an R function? A simplified version of what I'm trying to do is this:

plotgenerator<-function(x,y,...,...,...){
   plot(x,y,...)
   axes(...)
   legend(...)
   }

My thought was to use optional string arguments, like this:

plotgenerator<-function(x,y,plotargs="",axesargs="",legendargs=""){
   plot(x,y,plotargs)
   axes(axesargs)
   legend(legendargs)
   }

But that doesn't work. Does anyone know if something like this is possible? I have searched a lot for this, but a search string like "R ..." isn't actually very helpful ;)

like image 231
registrar Avatar asked Feb 22 '11 16:02

registrar


2 Answers

You could so something similar to your second choice if you use do.call, which allows you to pass the arguments to a function as a list. E.g. pass axesarg as a list and then in your function have: do.call(axes,axesarg) etc

For example:

outer_fxn <- function(inner_args=list(), ...) {
    do.call(inner_fxn, inner_args)
}

inner_fxn <- function(...) {
    # do stuff
}

# function call
outer_fxn(inner_args=list(a=1, b=2), outer_arg1=3, etc)

In the above, any arguments that should be handled by the inner_fxn ... should be passed in with in the inner_args list. The outer_fxn ... arguments are handled as usual.

like image 89
frankc Avatar answered Sep 30 '22 03:09

frankc


The first way that you show is not supported because there is no way for the parser to know which set of dots the caller wants the argument to go into.

You can capture the dots into a list and work from there with something like:

mydots <- list(...)

You can then make copies, remove items that are not appropriate for the function that you are calling, then use do.call (as has been mentioned) to call your function.

The second approach may be cleaner if you think the caller may want to send different values to different functions that have the same argument name. Again use do.call to pass the list of arguments.

like image 27
Greg Snow Avatar answered Sep 30 '22 02:09

Greg Snow