[R] recoding table dimensions interactively

Michael Friendly friendly at yorku.ca
Thu Jan 9 16:14:29 CET 2014


Given a 3+ way table, I'd like a simple, elegant way to flatten the 
table to a two-way
table, with some variables joined interactively to form the rows and 
others forming
the columns.  For example, starting with

 > str(UCBAdmissions)
  table [1:2, 1:2, 1:6] 512 313 89 19 353 207 17 8 120 205 ...
  - attr(*, "dimnames")=List of 3
   ..$ Admit : chr [1:2] "Admitted" "Rejected"
   ..$ Gender: chr [1:2] "Male" "Female"
   ..$ Dept  : chr [1:6] "A" "B" "C" "D" ...
 >

What I want is something similar to the result of ftable:

 > ftable(UCBAdmissions)
                 Dept   A   B   C   D   E   F
Admit    Gender
Admitted Male        512 353 120 138  53  22
          Female       89  17 202 131  94  24
Rejected Male        313 207 205 279 138 351
          Female       19   8 391 244 299 317

One way to do this is to convert to a data.frame, paste the factors 
together and then convert back to a table:

UCB.df <- as.data.frame(UCBAdmissions)
UCB.df$`Admit:Gender` <- paste(UCB.df$Admit, UCB.df$Gender, sep=':')
UCB.tab2 <- xtabs(Freq ~ `Admit:Gender` + Dept, data=UCB.df)
UCB.tab2

 > UCB.tab2
                  Dept
Admit:Gender        A   B   C   D   E   F
   Admitted:Female  89  17 202 131  94  24
   Admitted:Male   512 353 120 138  53  22
   Rejected:Female  19   8 391 244 299 317
   Rejected:Male   313 207 205 279 138 351
 >

But maybe there is a simpler, more elegant and general way to do this.

-- 
Michael Friendly     Email: friendly AT yorku DOT ca
Professor, Psychology Dept. & Chair, Quantitative Methods
York University      Voice: 416 736-2100 x66249 Fax: 416 736-5814
4700 Keele Street    Web:http://www.datavis.ca
Toronto, ONT  M3J 1P3 CANADA



More information about the R-help mailing list