Functions

RSE
Rpkg

Notes on functions

Author

Chi Zhang

Published

October 6, 2023

dot-dot-dot

Special argument .... This type of argument is varargs (variable arguments). The function can take any numbers of arguments.

Primary uses:

  • your function takes a function as an argument, and we want to pass additional arguments
  • S3 generic, need to allow methods to take extra arguments

Downsides:

  • need to explain where the arguments go to
  • misspelled argument will not raise an error

Example with mean(x, ...)

The ... can be something like na.rm = F.

Given that the first argument is being averaged upon, if a vector is not specified correctly, only the first element is being averaged; and the other elements are treated as additional arguments that are not necessarily used.

# mean(c(1,2,3)) 
mean(1, 2, 3)
[1] 1
mean(c(1, 2), 3)
[1] 1.5
fplus <- function(a, ...){
  list(sum(a), ...)
}
fplus(a = c(1,2,3))
[[1]]
[1] 6
fplus(a = c(1,2,3), 4)
[[1]]
[1] 6

[[2]]
[1] 4
f1 <- function(a, ...){
  args <- list(...)
  if('y' %in% names(args)){
    args$y <- 0.5 + args$y
    do.call(f2, args) # second arg need to be a list
  }else{
    a+1
  }

}
f2 <- function(y){return(y)}