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.
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.
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 .
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.
How about
newmean <- function(X, ...){
args <- as.list(substitute(list(...)))[-1L]
z<-list(X)
z<-c(z,args)
do.call(mean,z)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With