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)))
The output of a call to
tableis an object of classtable. This is basically anarray. 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 soIt looks like you want to then create a table of the relative proportions.
prop.tableis useful for this.you could also run
prop.tableon the original to get the row proportions (1 = rows, 2 = columns)The help file for
table(accessed by?tableorhelp('table')is detailed and contains links to the help files forprop.tableandaddmargins!