Say I had the following table DataTable
Cat1 | Cat2 | Val1 | Val2
--------------------------------------------
A | A | 1 | 2
A | B | 3 | 4
B | A | 5 | 6
B | B | 7 | 8
A | A | 2 | 4
A | B | 6 | 8
B | A | 10 | 12
B | B | 14 | 16
Which I wanted to Aggregate by Cat1 and Cat2, taking the Sum and Avg of Val1 and Val2 respectively, how might I acheive this?
Cat1 | Cat2 | Sum Val1 | Avg Val2
--------------------------------------------
A | A | 3 | 3
A | B | 9 | 6
B | A | 15 | 9
B | B | 21 | 12
I've achieved single variable aggregation with the aggregate function:
aggregate(
Val1
~ Cat1 + Cat2
data=DataTable,
FUNC=sum
)
but despite playing around with cbind, can't get the behaviour I want. I'm 24 hrs into learning R, so I'm not familiar enough with the concepts to fully understand what I've been doing (always dangerous!) but think this must be simple to achieve. |