Unpacking argument lists for ellipsis in R

mhermans picture mhermans · Aug 5, 2010 · Viewed 14.4k times · Source

I am confused by the use of the ellipsis (...) in some functions, i.e. how to pass an object containing the arguments as a single argument.

In Python it is called "unpacking argument lists", e.g.

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

In R for instance you have the function file.path(...) that uses an ellipsis. I would like to have this behaviour:

> args <- c('baz', 'foob') 
> file.path('/foo/bar/', args)
[1] 'foo/bar/baz/foob'

Instead, I get

[1] 'foo/bar/baz' 'foo/bar/foob'

where the elements of args are not "unpacked" and evaluated at the same time. Is there a R equivalent to Pythons *arg?

Answer

Jyotirmoy Bhattacharya picture Jyotirmoy Bhattacharya · Aug 5, 2010

The syntax is not as beautiful, but this does the trick:

do.call(file.path,as.list(c("/foo/bar",args)))

do.call takes two arguments: a function and a list of arguments to call that function with.