Search code examples
rmargincontingency

How to add the total sums to the table and get proportion for each cell in R


I'm trying to get a proportion for each cell by dividing each row by the row sum, but R gives me an Error saying,

Error in data.table$Country : $ operator is invalid for atomic vectors

How can I fix this? Also, how can add total sum values for the entire columns and rows to data.table? I get this values when I run addmargins(data.table), but I'd like to attach the sums to my dataframe.


Here's my code:

x = c(40,50,30,30,50)                
y = c(40,20,30,40,45)                              
data.table = rbind(x,y)   
data.table
dimnames(data.table)=list("Country"=c("England","Germany"),"Score"=c("Q-Score","T-score","X-score","Y-score","Z-score"))
addmargins(data.table)
table(data.table$Country,data.table$Score/rowSums(table(data.table&Country,data.table$Score)))

Solution

  • The output of a call to table is an object of class table. This is basically an array. You cannot use $ to reference arrays or atomic vectors. (Hence the error).

    If you want to assign the results of addmargins(data.table) to an object, then you are more than free to do so

    margin_table <- addmargins(data.table)
    

    It looks like you want to then create a table of the relative proportions.

    prop.table is useful for this.

     prop.table(margin_table)
    
             Score
    Country      Q-Score    T-score X-score    Y-score    Z-score       Sum
      England 0.02666667 0.03333333    0.02 0.02000000 0.03333333 0.1333333
      Germany 0.02666667 0.01333333    0.02 0.02666667 0.03000000 0.1166667
      Sum     0.05333333 0.04666667    0.04 0.04666667 0.06333333 0.2500000
    

    you could also run prop.table on the original to get the row proportions (1 = rows, 2 = columns)

     prop.table(data.table, margins = 1)
          Score
    Country     Q-Score   T-score   X-score   Y-score   Z-score
      England 0.2000000 0.2500000 0.1500000 0.1500000 0.2500000
      Germany 0.2285714 0.1142857 0.1714286 0.2285714 0.2571429
    

    The help file for table (accessed by ?table or help('table') is detailed and contains links to the help files for prop.table and addmargins!