Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an ellipsis (`...`) object from scratch?

Tags:

r

I found the solution for passing missing arguments to functions with defaults using such a pseudo code:

wrapperfX<-function(x)
{
    ...<-if(missing(x){
            list()
        }else{
            list(x=x)
        }
    targetf(...)
}

How much are these things allowed in R?

like image 397
Adam Ryczkowski Avatar asked Sep 07 '13 07:09

Adam Ryczkowski


2 Answers

The trick you are looking for is perhaps to use do.call which lets you call a function and specify the arguments as a list:

wrapperfX <- function(x){
  dots<-if(missing(x)){
    list()
  }else{
    list(x=x)
  }
  do.call(targetf,dots)
}

This lets you specify named arguments as well if the list elements have names.

> do.call(log,list(x=10,base=10))
[1] 1

is equivalent to

log(x=10,base=10)

If the function you are calling is expressed in terms of dot-dot-dots, then the arguments will me matched in the same way as if you'd put them in the function call.

[also you had a missing parenthesis in, appropriately, missing((x){ :) ]

like image 104
Spacedman Avatar answered Dec 19 '22 20:12

Spacedman


If your function depends on the unevaluated expression, you may want to use substitute, to avoid evaluation of the ... calls inside the wrapper.

Example:

f <- function(...) deparse(as.list(substitute(list(...)))[-1L])

wrap <- function(x){
    L <- if(missing(x)) list() else list(x)
    do.call(f, L)
}

wrap2 <- function(x){
    L <- if(missing(x)) list() else list(substitute(x))
    do.call(f, L)
}

Note how wrap2 doesn't "touch" the arguments:

f(1+2+3)      # "list(1 + 2 + 3)"
wrap(1+2+3)   # "list(6)"
wrap2(1+2+3)  # "list(1 + 2 + 3)"

For empty calls, they are indistinguishable:

f()      # "list()"
wrap()   # "list()"
wrap2()  # "list()"
like image 38
Ferdinand.kraft Avatar answered Dec 19 '22 19:12

Ferdinand.kraft