1

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.

Luigi Tiburzi
  • 4,265
  • 7
  • 32
  • 43
  • 2
    Hi, your shown output does not correspond to the actual output, could you edit that? And what should the final result look like? – jay.sf May 28 '20 at 07:22
  • What kind of percentages are you exactly looking for? I doubt that it's a good idea to first calculate the marginal sums and then get some percentages... ;-) – Andri Signorell May 29 '20 at 13:33
  • I need the percentage of people sentenced to death. I achieved this with p_yes = function(x) x[1]/sum(x); mytable = addmargins(mytable, margin=c(3), FUN = list(p_yes)) – Luigi Tiburzi Jun 01 '20 at 09:46

1 Answers1

2

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
Luigi Tiburzi
  • 4,265
  • 7
  • 32
  • 43