Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking argument lists for ellipsis in R

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?

like image 687
mhermans Avatar asked Aug 05 '10 11:08

mhermans


People also ask

What type of arguments can a function take in R?

Arguments are the parameters provided to a function to perform operations in a programming language. In R programming, we can use as many arguments as we want and are separated by a comma. There is no limit on the number of arguments in a function in R.

How do you find arguments in R?

args() function in R Language is used to get the required arguments by a function. It takes function name as arguments and returns the arguments that are required by that function.


1 Answers

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.

like image 53
Jyotirmoy Bhattacharya Avatar answered Oct 13 '22 08:10

Jyotirmoy Bhattacharya