Learning how to deal with ... in functions in R

Viewed 72

This is my function. Basically I want to include a if else statement inside it but controlling by the length of the arguments that I use in ...:

This is what Ive tried so far, and it is wrong:

  soma_mtcars<-function(data,...){
    if(length(...) < 2){
     sum_df<- data %>% group_by() %>% summarise(total = sum(disp))
    }
    else(
      sum_df<- data %>% group_by() %>% summarise(total = sum(disp))
    )
  }

Of course the problem is in length(...) < 2. How can I deal with it?

And I would like to have, for example, outputs for: soma_mtcars(mtcars,cyl) and soma_mtcars(mtcars, cyl, disp)

2 Answers

You can use nargs(), which gives you the total number of arguments (i.e. including your data argument):

soma_mtcars <- function (data, ...) {
    if (nargs() < 3L) { …
}

… or you can pass ... list, and get the length of its result:

soma_mtcars <- function (data, ...) {
    if (length(list(...)) < 2L) { …
}

Either of these will return the length of dot dot dot. The first one does it without evaluating dot dot dot.

len_noeval <- function(...) ...length()

len_eval <- function(...) length(list(...))

# test

len_noeval(11, print(12), 13)
## [1] 3

len_eval(11, print(12), 13)
## [1] 12
## [1] 3
Related