Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Margin totals in xtabs

Tags:

r

If you have 2 cross classifying variables you can use rowSums and colSums to produce margin totals on an xtabs output. But how can it be done if you have 3 classifying variables (ie margin totals in each sub table)?

like image 706
James Avatar asked Apr 02 '10 13:04

James


2 Answers

Aniko mentioned this in a comment, but it was never provided as an answer.

I found this independently and then noticed it was here in a comment, so credit to Aniko for getting it first.

addmargins is the answer:

For a given table one can specify which of the classifying factors to expand by one or more levels to hold margins to be calculated. One may for example form sums and means over the first dimension and medians over the second. The resulting table will then have two extra levels for the first dimension and one extra level for the second. The default is to sum over all margins in the table. Other possibilities may give results that depend on the order in which the margins are computed. This is flagged in the printed output from the function.

like image 110
dsz Avatar answered Sep 29 '22 21:09

dsz


The general approach is to use the apply function, but specifically for totals the margin.table function might be more convenient:

#create 3 factors
a <- gl(2,4, length=20)
b <- gl(3,2, length=20)
d <- gl(4,2, length=20)
# table
tt <- xtabs(~a+b+d)

# marginal sums
margin.table(tt, 1)
apply(tt, 1, sum)  #same answer

#multi-way margins
margin.table(tt, 1:2)
apply(tt, 1:2, sum)  #same answer
like image 27
Aniko Avatar answered Sep 29 '22 22:09

Aniko