Anke
Anke

Reputation: 651

Function call with additional custom arguments

I'm trying to wrap my head around ellipsis in R. I have a function and want to be able to pass additional arguments to the function as needed, for example whether or not to return a df or similar. Can I not specify variable names? This is a very simplified example and I want to be able to make this optional to keep function calls as easy and clean as possible with multiple possible conditionals within the function for various scenarios.

 custom.fun<-function(x, y, z, ...){

 a<-sum(x, y, z)

   if (exists('return.var') && return.var=='yes'){
     return(a)
   }
 }

 A<-custom.fun(1,2,3,return.var='yes')

This returns Null, as it is obviously not passing on return.var.

Upvotes: 0

Views: 61

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

I guess you can do something similar to this, capture all the optional argument in list and check if any of them have the required name and value.

custom.fun<-function(x, y, z, ...){
   opt_args <- list(...)
   a <- sum(x, y, z)
   if (any(names(opt_args) == 'return.var' & opt_args == 'yes'))
       return(a)
   else 
       return('No arg')
}

custom.fun(1,2,3,return.var = 'yes')
#[1] 6

custom.fun(1,2,3,var = 'yes')
#[1] "No arg"

custom.fun(1,2,3,var='no', return.var = 'yes')
#[1] 6

Upvotes: 2

Related Questions