Shanthan Kesharaju Shanthan Kesharaju - 1 month ago 8
R Question

Calculations proportions of a three way table


Possible Duplicate:

How to create a prop.table() for a three dimension table?




I am new to R, and I have been working on a three way table and need some help. Here is the table description via
dput
:

mytable <- structure(c(42L, 151L, 313L, 69L, 22L, 46L, 47L, 24L, 17L, 36L, 108L, 16L), .Dim = c(2L, 2L, 3L), .Dimnames = list(c("0", "1" ), c("female", "male"), c("adult", "child", "unknown")), class = "table")


I would like to access elements of this table by using the attribute names. For example:
mytable["0"]["female"]["adult"]
Is it possible to do this ?

Also, I am trying to calculate proportions. Here is my table....

, , adult

female male
0 42 313
1 151 69

, , child

female male
0 22 47
1 46 24

, , unknown

female male
0 17 108
1 36 16


I would like to calculate proportions for age group-sex-0|1. When I run
prop.table(mytable)
it is calculating proportions of the cells, but it is considering all the three age groups.

, , adult

female male
0 0.04713805 0.35129068
1 0.16947250 0.07744108

, , child

female male
0 0.02469136 0.05274972
1 0.05162738 0.02693603

, , unknown

female male
0 0.01907969 0.12121212
1 0.04040404 0.01795735


I want proportions for each age group and sex. For example: Of all the adults, females with 1 are 78 %. How do we do this ?

Answer

Is this what you are chasing?

The data:

test <- structure(c(42L, 151L, 313L, 69L, 22L, 46L, 47L, 24L, 17L, 36L, 108L, 16L), .Dim = c(2L, 2L, 3L), .Dimnames = list(c("0", "1" ), c("female", "male"), c("adult", "child", "unknown")), class = "table") 

Get the column percentages (2) within each sub-table (3):

prop.table(test,c(2,3))

Results in:

, , adult

     female      male
0 0.2176166 0.8193717
1 0.7823834 0.1806283

, , child

     female      male
0 0.3235294 0.6619718
1 0.6764706 0.3380282

, , unknown

     female      male
0 0.3207547 0.8709677
1 0.6792453 0.1290323