Anton Tarasenko
Anton Tarasenko

Reputation: 8455

Ellipsis expansion in nested functions: Error "'...' used in an incorrect context"

I have a very simple piece of code that produces:

afun <- function(a) {
  return(bfun(...))
}
bfun <- function(...) {
  return(a + 1)
}

> afun(1)
Error in afun(1) : '...' used in an incorrect context

But what R doesn't like here?

Upvotes: 7

Views: 12172

Answers (2)

Aleksandar Kittov
Aleksandar Kittov

Reputation: 21

If you want afun to return function with variable number of the arguments just return bfun as a return value of afun. In R these are called closures

This is what you get:

afun <- function(a) {
        print(a)
        function (b, ...){
                print(paste(b, ..., sep = " "))
        } 
}

The result is:

bfun <- afun("in afun body")    # "in afun body from print(a)

bfun("arg1")                    # "arg1" from  print(paste(b, ..., sep = " ")) 
bfun("arg1", "arg2", "arg3")    # "arg1 arg2 arg3" from  print(paste(b, ..., sep = " "))

Upvotes: 2

joran
joran

Reputation: 173517

In your function afun:

afun <- function(a) {
  return(bfun(...))
}

the ... is simply an argument (with no default value), just like any other. It doesn't mean "automatically suck up all arguments passed to the parent function". It just as if you had defined bfun as:

bfun <- function(b) {
  return(b + 1)
}

and then tried to do:

afun <- function(a) {
  return(bfun(b))
}

In order for a to be passed on to bfun, you either have to gather that argument yourself using something like match.call, or you have to hard code it (e.g. return(bfun(a))), or you have to use ... as an argument (and the only argument) to afun.

Typically, ... is used for passing additional arguments on to a subsequent function.

Upvotes: 7

Related Questions