Learn R Programming

gdata (version 2.7.1)

aggregate.table: Create 2-Way Table of Summary Statistics

Description

Splits the data into subsets based on two factors, computes a summary statistic on each subset, and arranges the results in a 2-way table.

Usage

aggregate.table(x, by1, by2, FUN=mean, ...)

Arguments

x
data to be summarized
by1
first grouping factor.
by2
second grouping factor.
FUN
a scalar function to compute the summary statistics which can be applied to all data subsets. Defaults to mean.
...
Optional arguments for FUN.

Value

  • Returns a matrix with one element for each combination of by1 and by2.

See Also

aggregate, tapply, interleave

Examples

Run this code
# Useful example:
#
# Create a 2-way table of means, standard errors, and # obs

g1 <- sample(letters[1:5], 1000, replace=TRUE)
g2 <- sample(LETTERS[1:3], 1000, replace=TRUE )
dat <- rnorm(1000)

stderr <- function(x) sqrt( var(x,na.rm=TRUE) / nobs(x) )

means   <- aggregate.table( dat, g1, g2, mean )
stderrs <- aggregate.table( dat, g1, g2, stderr )
ns      <- aggregate.table( dat, g1, g2, nobs )
blanks <- matrix( "", nrow=5, ncol=3)

tab <- interleave( "Mean"=round(means,2),
                   "Std Err"=round(stderrs,2),
                   "N"=ns, "" = blanks, sep="" )

print(tab, quote=FALSE)

Run the code above in your browser using DataLab