Variable Numbers of Arguments (...)

Some applications are much more straightforward if the number of arguments does not need to be specified in advance. There is a special formal name... (triple dot) which is used in the argument list to specify that an arbitrary number of arguments are to be passed to the function. Here is a function that takes any number of vectors and calculates their means and variances:

many.means <- function (...){
  data <- list(...)
  n<- length(data)
  means <- numeric(n)
  vars <- numeric(n)
  for (i in 1:n) {
      means[i]<-mean(data[[i]])
      vars[i]<-var(data[[i]])
  }
  print(means)
  print(vars)
  invisible(NULL)
}

The main features to note are these. The function definition has ... as its only argument. The ‘triple dot’ argument allows ... the function to accept additional arguments of unspecified name and number, and this introduces tremendous flexibility into the structure and behaviour of functions. The first thing done inside the function is to create an object called data out of the list of vectors that are actually supplied in any particular case. The length of this list is the number of vectors, not the lengths of the vectors themselves (these could differ from one vector to another, as in the example below). Then the two output variables (means and vars) are defined to have as many elements as there are vectors in the parameter list. The loop goes from 1 to the number of vectors, and for each vector uses the built-in functions mean and var to compute the answers ...

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.