Re: [R] crosstab for n-way contingency tables

From: hadley wickham <h.wickham_at_gmail.com>
Date: Wed 31 Aug 2005 - 10:33:42 EST

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



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Wed Aug 31 10:40:29 2005

This archive was generated by hypermail 2.1.8 : Sun 23 Oct 2005 - 16:09:25 EST