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)?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With