Combine two flat contingency tables (ftable) in R?

1.5k views Asked by At

I am making a series of frequency/contingency tables and ideally I'd like to put them together into one

tab1 <- ftable(xtabs( ~Survived+Age, Titanic))
tab2 <- ftable(xtabs( ~Class+Age, Titanic))

rbind puts them together, but you lose the row and column names.

I'm wondering if I should try grabbing the levels from the variables and put them in (but that seems like a good chance to get the wrong order put in). I guess I could try converting to a data.frame and then combining, but I'd like to get some input.

2

There are 2 answers

0
Sven Hohenstein On

Combining the tables does not allow multiple names for the row variables.

tab <- rbind(tab1, tab2)
class(tab) <- "ftable"
attr(tab, "col.vars") <- attr(tab1, "col.vars")
attr(tab, "row.vars") <- list(Var = unlist(c(attr(tab1, "row.vars"), 
                                             attr(tab2, "row.vars"))))

tab
#      Age Child Adult
# Var                 
# No           8     8
# Yes          8     8
# 1st          4     4
# 2nd          4     4
# 3rd          4     4
# Crew         4     4
0
acmw On

I had this problem also. I ended up generating the contingency tables as a matrix, where you can specify specific row and column names, then you can convert back to data.frame or save as a .csv file.