rfunctionoptional-arguments

Passing in list of optional arguments in R


I am trying to simplify my code by making a list of variables that I can pass into a function as optional arguments. The function has other arguments as well that would be specified directly. For example:

foo <- function(data, ..., func = mean, cross_depth = NULL, data_table = FALSE){
what function does here}

varx <- list("var1", "var2", "var3")

foo(data, varx, func = func, data_table = TRUE, cross_depth = 3)

The list of optional arguments is always changing, and this function is used repeatedly, so it helps to be able to specify these variables outside of the function itself. I have tried using do.call in various ways, but it keeps throwing errors. Any help is much appreciated!


Solution

  • I think the most straightforward way to handle this kind of pattern is to give the function an extra_args parameter that accepts an arbitrary list (and defaults to an empty list if you want to ignore it):

    foo <- function(data, extra_args = list(), func = mean, 
                    cross_depth = NULL, data_table = FALSE) {
      # Do stuff 
    }
    

    Which allows:

    varx <- list("var1", "var2", "var3")
    
    foo(data, varx, func = func, data_table = TRUE, cross_depth = 3)