Dienstag, 4. September 2012

Flexible arguments for R functions

How can we remain flexible concerning arguments of an R function used within a user function. Say we want a histogram to be included in our plot and be able to define all of it's arguments.
I found a good solution in some R-Core-code (don't remember exactly where...).
It goes like that:

myFunction <- function( x, main = "", args.hist = NULL, ... ) {

  # define default arguments
  args.hist1 <- list(x = x, xlab = "", ylab = "", freq = FALSE,
      xaxt = "n", xlim = NULL, ylim = NULL, main = main, las = 1,
      col =  "white", cex.axis = 1.2)
  # override default arguments with user defined ones
  if (!is.null(args.hist)) {
    args.hist1[names(args.hist)] <- args.hist
  }
  # call function by means of do.call with the list of arguments
  # we can even filter the arguments by name here...
  res <- do.call("hist", c(args.hist1[names(args.hist1) %in%
      c("x", "breaks", "include.lowest", "right", "nclass")],
      plot = FALSE))
}

The function call would then be:
  myFunction( x=1:10, args.hist = list(right = TRUE) )

So we have a fine control over which arguments we want to be passed (include.lowest, right) and which ones not (ex. col, cex.axis).

Keine Kommentare: