Expands a contingency table to a data frame where each observation in the table becomes a single observation in the data frame with corresponding information for each for each combination of the table dimensions.
expand_table(x)
A data frame with the table or matrix expanded
expand_table(diag(3))
#> Var1 Var2
#> 1 A A
#> 5 B B
#> 9 C C
m <- matrix(c(2, 1, 3, 0, 0, 2), 3)
expand_table(m)
#> Var1 Var2
#> 1 A A
#> 1.1 A A
#> 2 B A
#> 3 C A
#> 3.1 C A
#> 3.2 C A
#> 6 C B
#> 6.1 C B
result <- expand_table(UCBAdmissions)
head(result)
#> Admit Gender Dept
#> 1 Admitted Male A
#> 1.1 Admitted Male A
#> 1.2 Admitted Male A
#> 1.3 Admitted Male A
#> 1.4 Admitted Male A
#> 1.5 Admitted Male A
# Combine into table again
xtabs(~Admit + Gender + Dept, data=result)
#> , , Dept = A
#>
#> Gender
#> Admit Male Female
#> Admitted 512 89
#> Rejected 313 19
#>
#> , , Dept = B
#>
#> Gender
#> Admit Male Female
#> Admitted 353 17
#> Rejected 207 8
#>
#> , , Dept = C
#>
#> Gender
#> Admit Male Female
#> Admitted 120 202
#> Rejected 205 391
#>
#> , , Dept = D
#>
#> Gender
#> Admit Male Female
#> Admitted 138 131
#> Rejected 279 244
#>
#> , , Dept = E
#>
#> Gender
#> Admit Male Female
#> Admitted 53 94
#> Rejected 138 299
#>
#> , , Dept = F
#>
#> Gender
#> Admit Male Female
#> Admitted 22 24
#> Rejected 351 317
#>