Skip to content

How to convert a list to a ... argument for a function

3 messages · Richard R. Liu, Duncan Murdoch, Charles C. Berry

#
Hi, 


I have a function f <- function(..., func){ something }, where func is a
function of the form function(...). ?I would like to pass func all the arguments
passed to f except the last. ?I know that I can manipulate the variable number
of arguments passed to f by converting ... to a list, i.e., arglist <-
list(...). ?But how do I pass func the first n-1 list items of arglist (n <-
length(arglist)), as n-1 arguments, not as one list of n-1 items?


Regards,
Richard



Richard R. Liu
richard.liu at pueo-owl.ch
#
On 05/10/2010 2:23 PM, Richard R. Liu wrote:
Do you know the name of the last one?  If so, just declare it as an 
argument to f, and it won't be caught by ... .

Do you know how many arguments there are?  Then the barely documented 
..1, ..2 etc might work for you.

Otherwise, convert it to a list, and use do.call(func, args), where args 
is the list without the last element.

Duncan Murdoch
#
On Tue, 5 Oct 2010, Richard R. Liu wrote:

            
One way:

foo <- function(...,func){
 	mc <- match.call()
 	mc[[1]] <-mc$func
 	mc$func <- NULL
 	mc[[ length(mc) ]] <- NULL
 	eval(mc) }

foo(1,2,3,4,func=c)
foo(1,2,4,3,func=sum)


or perhaps you meant like this:

foo <- function(...,func){
         mc <- match.call()
         mc[[1]] <-mc$func
         mc$func <- NULL
         eval(mc) }

foo(1,2,3,4,func=c)
foo(1,2,4,3,func=sum)


HTH,

Chuck
Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901