Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

function

r

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?

like image 439
Anton Tarasenko Avatar asked Dec 13 '13 18:12

Anton Tarasenko


2 Answers

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.

like image 74
joran Avatar answered Nov 20 '22 15:11

joran


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 = " "))
like image 37
Aleksandar Kittov Avatar answered Nov 20 '22 13:11

Aleksandar Kittov