How do I get Pivots with subtotals (like in MS Excel Pivot Tables) in R?
I am using dcast
from reshape2
package to create pivots in R. I also got grand totals working using rowSums
and colSums
. I admit I do not understand the intricacies in the dcast
parameter set. I just know how to create the pivot and the help file is going over my head. It will be extremely helpful if someone can solve this using dcast
(I suspect it can do it all), and explain the parameters necessary for the solution.
I am using this code (C2 has two factors, X1 & X2):
PIV <- dcast(DF, C1~C2, value.var="C3", sum)
I am not getting what all these margins, subset, fills or drop does. The help file seems overly obtuse, and I did not get much help on the internet as well.
Sample Pivot (without subtotal, T is total):
C1 X1 X2 T
a 12 1 13
a 14 2 16
b 16 3 19
b 11 4 15
b 8 5 13
T 61 15 76
Sample Expected Pivot (with subtotal t, T is total)
C1 X1 X2 T
a 12 1 13
a 14 2 16
ta 26 3 29
b 16 3 19
b 11 4 15
b 8 5 13
tb 35 12 47
T 61 15 76