Functions with a variable number of arguments

The ellipsis ... are used in the argument list of functions to handle a variable number of arguments.

Summing a bunch of things

Here is a simple example.

mySum <- function(...) {
    return(sum(unlist(list(...))))
}

This can be applied as follows.

mySum(3, 1, 2, 3)
## [1] 9
mySum(1:4, 1, 2, 3, 4)
## [1] 20

Plotting a function

Here is a more typical example. We want to plot a function that may take some additional parameters.

myCurve <- function(f, left = 0, right = 1, nx = 100, ...) {
    x <- seq(left, right, length = nx)
    plot(x, f(x, ...), xlim = c(left, right), ylab = "y", type = "l", col = "RED", 
        lwd = 2)
}

First try it with the power function.

power <- function(x, p) {
    x^p
}

which results in

myCurve(power, p = 2)

plot of chunk unnamed-chunk-5

myCurve(power, p = 0.5)

plot of chunk unnamed-chunk-5

Or we could use the built-in normal density function dnorm() to do

myCurve(dnorm, left = -10, right = +10, mean = 3, sd = 2)

plot of chunk unnamed-chunk-6

More complicated argument lists

To see how ellipses work in a more complicated argument list we use the two functions vArg and wArg.

vArg <- function(x, y, ..., z) {
    wArg(x, ...)
    qArg <- list(...)
    print(c(qArg$o, qArg$p))
}
wArg <- function(a, ...) {
    print(list(a, ...))
}

We call vArg as follows

vArg(1, 2, o = 3, p = 4, z = 4, 5)
## [[1]]
## [1] 1
## 
## $o
## [1] 3
## 
## $p
## [1] 4
## 
## [[4]]
## [1] 5
## 
## [1] 3 4

and we see that x=1, y=2, z=4, and list(...)=list(o=3,p=4,5).