# [R] pooling categories in a contingency table

Michael Friendly friendly at yorku.ca
Wed Apr 24 16:29:30 CEST 2002

```John Fox helped show me how to collapse the categories, pooling
frequencies, in an n-way table, using levels()<- on an equivalent
data frame:

# create a table
sex <- c("Male", "Female")
age <- letters[1:6]
education <- c("low", 'med', 'high')
data <- expand.grid(sex=sex, age=age, education=education)

counts <- rpois(36, 100)
data <- cbind(data, counts)
t1 <- xtabs(counts ~ sex + age + education, data=data)

# collapse age to 3 levels
levels(data\$age) <- c("A", "A", "B", "B", "C", "C")
t2 <- xtabs(counts ~ sex + age + education, data=data)

I'd like to generalize this to a function, collapse.table.  Here's what
I tried:

collapse.table <- function(table, ...) {
nargs <- length(args <- list(...))
if (!nargs)
return(table)
if (inherits(table, "table")) {
table <- as.data.frame.table(table)
freq <- table[,"Freq"]
tvars <- dimnames(table)
}
names <- names(args)
print(cat("names: ", names, "\n"))
for (i in 1:nargs) {
vals <- args[[i]]
nm <- names[[i]]
print(cat("vals: ", vals, "\n"))
print(cat("nm: ", nm, "\n"))
levels(table\$nm) <- vals
}
terms <- paste(tvars, sep = '+')
result <- xtabs(freq ~ terms, data=table)
}

>From the output below, I see what the problem is, but don't know
how to fix it:

> collapse.table(t1, age=c("A", "A", "B", "B", "C", "C"))
names:  age
NULL
vals:  A A B B C C
NULL
nm:  age
NULL
Error in "levels<-.default"(*tmp*, value = c("A", "A", "B", "B", "C",  :
attempt to set an attribute on NULL
> traceback()
3: "levels<-.default"(*tmp*, value = c("A", "A", "B", "B", "C",
"C"))
2: "levels<-"(*tmp*, value = c("A", "A", "B", "B", "C", "C"))
1: collapse.table(t1, age = c("A", "A", "B", "B", "C", "C"))

Can someone help?

-Michael

--
Michael Friendly              friendly at yorku.ca
York University               http://www.math.yorku.ca/SCS/friendly.html
Psychology Department
4700 Keele Street             Tel:  (416) 736-5115 x66249
Toronto, Ontario, M3J 1P3     Fax:  (416) 736-5814
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```