Dienstag, 18. September 2012

Conditional Mosaics: Cotabplot

Fine implementation, thanks to Achim Zeileis.

library(vcd)
data("Punishment", package = "vcd")
pun <- xtabs(Freq ~ memory + attitude + age + education, data = Punishment)
cotabplot(~ memory + attitude | age + education, data = pun, panel = cotab_coindep,
  n = 5000, type = "mosaic", test = "maxchisq", interpolate = 1:2 )

Donnerstag, 13. September 2012

Conversions

How can we split a matrix columnwise to a list?
m <- matrix(rnorm(10 * 2), ncol = 2)

The first solution uses a double conversion via a data.frame:
as.list(as.data.frame(m))

The second uses split:
split(x=t(m), f=1:ncol(m))

The third solution works with lapply:
lapply( seq_len(ncol(m)), function(k) m[,k])

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).