Search code examples
rcontingency

Add margins to multi-way tables in R


I have the following code in R to build a three-way contingency table:

txt="   death_p yes no
v_race  d_race      
white   white   53  414
black   11  37
black   white   0   16
black   4   139"

mytable = as.table(read.ftable(textConnection(txt)))
mytable = addmargins(mytable, margin=c(1))

It prints correctly

             death_p yes  no
v_race d_race                
white  white           53 414    
       black           11  37
black  white            0  16
       black            4 139
Sum    white           53 430
       black           15 176

I'd like to add a "percentage_yes" after the column "no" preserving the structure of the table.

                 death_p yes  no  %yes
v_race d_race                
white  white             53   414  0.11    
       black             11   37   0.00
black  white             0    16   0.11
       black             4    139  0.23
Sum    white             53   430  0.28
       black             15   176  0.79

I've tried with

subset(as.data.frame(prop.table(mytable, c(1,2))), death_p=="yes", select=c("Freq"))

but I don't know how to add this new column to the table using Abind (from DescTools). I don't know if there is possibly a better way to accomplish this. Thanks in advance for your help.


Solution

  • For those who might be interested, I managed to do this by defining a function to calculate the percentage and then pass it to addmargins.

    p_yes = function(x) x[1]/sum(x)
    mytable = addmargins(mytable, margin=c(3), FUN = list(p_yes))
    

    It gives

                   death_p   yes     no     %yes
    v_race d_race                
    white  white             53.00   414.00  0.11    
           black             11.00   37.00   0.00
    black  white             0.00    16.00   0.11
           black             4.00    139.00  0.23
    Sum    white             53.00   430.00  0.28
           black             15.00   176.00  0.79