Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: using a list for ellipsis arguments

I have run into a situation where I need to take all the extra arguments passed to an R function and roll them into an object for later use. I thought the previous question about ellipses in functions would help me, but I still can't quite grasp how to do this. Here is a very simple example of what I would like to do:

newmean <- function(X, ...){
  args <- as.list(substitute(list(...)))[-1L]
  return(mean(X, args))
}

I've tried a number of different formulations of args in the above example and tried unlisting args in the return call. But I can't make this work. Any tips?

I realize that I could do this:

newmean <- function(X, ...){
    return(mean(X, ...))
}

But I need to have the ... arguments in an object which I can serialize and read back into another machine.

like image 727
JD Long Avatar asked Jun 29 '10 16:06

JD Long


People also ask

How do you use the three dots function in R?

If you have used R before, then you surely have come across the three dots, e.g. In technical language, this is called an ellipsis. And it means that the function is designed to take any number of named or unnamed arguments.

Does order of arguments matter in R?

Argument Order MattersThe order or arguments supplied to a function matters. R has three ways that arguments supplied by you are matched to the formal arguments of the function definition: By complete name: i.e. you type main = "" and R matches main to the argument called main .

What are R named arguments?

Arguments are always named when you define a function. When you call a function, you do not have to specify the name of the argument. Arguments are optional; you do not have to specify a value for them. They can have a default value, which is used if you do not specify a value for that argument yourself.


1 Answers

How about

newmean <- function(X, ...){
  args <- as.list(substitute(list(...)))[-1L]
  z<-list(X)
  z<-c(z,args)
  do.call(mean,z)
}
like image 109
Jyotirmoy Bhattacharya Avatar answered Sep 28 '22 09:09

Jyotirmoy Bhattacharya