8

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)))
mnel
  • 113,303
  • 27
  • 265
  • 254
Pirate
  • 311
  • 1
  • 5
  • 12

1 Answers1

14

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!

mnel
  • 113,303
  • 27
  • 265
  • 254
  • thanks for the help on adding margins! actually I wasn't trying to get the relative proportions. I'm trying to divide the row for England by it's rowsum and divide the German row by its rowsum. could you show me how to do this using this table? or should I make a different data? – Pirate Oct 30 '12 at 03:38
  • 1
    See my edit. Read the help files! If what you are doing is a standard thing to do, there will almost certainly be a function in a package for it. – mnel Oct 30 '12 at 03:48