[R] crosstab for n-way contingency tables

hadley wickham h.wickham at gmail.com
Wed Aug 31 02:33:42 CEST 2005


Hi Isotta,

You can do this with the reshape package (available from CRAN). eg

install.packages("reshape")
library(reshape)

data(singer, package="lattice")
singer$type <- c("drammatic", "spinto", "lirico-spinto", "lirico",
"leggero")[sample(1:5, 235, replace=T)]
singer$school <- c("german", "italian", "french", "russian",
"anglo-saxon", "other")[sample(1:6, 235, replace=T)]
singer$repertory <- c("opera", "Lieder", "oratorio",
"operetta")[sample(1:4, 235, replace=T)]

# First deshape the data (this puts it in a form easy to reshape)
singer_d <- deshape(singer, id=c("type", "school", "repertory",
"voice.part"), m="height")

# You can do things like
reshape(singer_d, type  ~ school, length, subset=variable=="height")
reshape(singer_d, type  ~ school, mean, subset=variable=="height")

# or with margins
reshape(singer_d, type + school ~ ., length,
subset=variable=="height", margins=c("type","grand_row"))

# or with multiple stats
opera.sum <- function(x) c(min=min(x), mean=mean(x), max=max(x))
reshape(singer_d, type + school ~ ., opera.sum, subset=variable=="height")

# What you'd want for your data, but doesn't work well with this example
# and is going to be a big table regardless!
reshape(singer_d, type + voice.part ~ school + repertory, length)

There's some more info available at http://had.co.nz/reshape but I'm
still working on it.

Hadley




More information about the R-help mailing list