Search code examples
rsumaggregatelevels

R: sum at different levels


I have a dataset X as:

customer_id event_type tot_count
931 1 5
231 2 6
231 1 3
333 3 9
444 1 1
931 3 3
333 1 21
444 2 43

I need a sum at customer_id and event_type level. This is a 1 line code in SQL as:

select customer_id, event_type, sum(tot_count) from X group by 1,2

I need the same operation in R.


Solution

  • You can use the aggregate function:

    aggregate(tot_count ~ customer_id + event_type, X, sum)
    
     customer_id event_type tot_count
    1         231          1         3
    2         333          1        21
    3         444          1         1
    4         931          1         5
    5         231          2         6
    6         444          2        43
    7         333          3         9
    8         931          3         3