views:

92

answers:

2

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.

+3  A: 

How about

newmean <- function(X, ...){
  args <- as.list(substitute(list(...)))[-1L]
  z<-list(X)
  z<-c(z,args)
  do.call(mean,z)
}
Jyotirmoy Bhattacharya
@jmoy, you've been helping me a lot lately! Thanks again.
JD Long
@JD, am learning stuff too in trying to answer your questions.
Jyotirmoy Bhattacharya
A: 

Can I ask what's the difference between args <- list(...) and args <- as.list(substitute(list(...)))[-1L]? And what's the do.call magic here?

since for this question, code below works too

newmean <- function(X, ...){ args <- list(...); do.call(mean,c(list(X),args)) }

But this does not work: newmean <- function(X, ...){ args <- list(...); mean(c(list(X),args)) } `

ahala
the do.call magic (as well as I can tell) is that do.call will construct and execute a function from a list of arguments. This works for functions where the function doesn't take a list as an argument. That was the problem I was having. I kept trying to pass a list to mean() and mean() doesn't expect a list for arguments. as for the list(...) vs as.list(substitute(list(...)))[-1L] the previous ellipses question might help: http://stackoverflow.com/questions/3057341/how-to-use-rs-ellipsis-feature-when-writing-your-own-function
JD Long