Search code examples
rfunctional-programmingellipsis

Passing variable number of arguments to R function


I have a function that can receive variable (and unknown) number of arguments. The simplest example would be

test <- function(...){
       print(length(list(...)))
}

This function is called from a Shiny app where user provides input arguments separated by comma. Let's assume that I parse the arguments and I have them in a vector

args <- c(1,2,3,4)

How can I pass these arguments to the function test without explicitly calling

test(args[1], args[2], args[3], args[4])

In my case the above solution is not good, since the number of arguments is unknown and I cannot hard code it.

I cannot also modify the function test to receive all the arguments as a list (the function is part of a package which I can't/don't want to modify)


Solution

  • We can use do.call. args is a vector, do.call needs a list of arguments, we can convert args to list using as.list.

    do.call(test, as.list(args))
    #[1] 4