2013-03-13 62 views
1

我有一個數據集X爲:R:總和在不同級別

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 

我需要在customer_idevent_type電平的總和。 這是SQL 1行代碼:

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

我需要R.

回答

5

相同的操作,您可以使用aggregate功能:

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 
+0

(+1)打我吧 – NPE 2013-03-13 07:29:46

3

爲了好玩,這裏有更多選項:

既然您知道SQL,sqldf

> sqldf("select customer_id, event_type, sum(tot_count) from mydf group by 1,2") 
    customer_id event_type sum(tot_count) 
1   231   1    3 
2   231   2    6 
3   333   1    21 
4   333   3    9 
5   444   1    1 
6   444   2    43 
7   931   1    5 
8   931   3    3 

如果你有大量的數據,data.table

> library(data.table) 
> DT <- data.table(mydf, key = c("customer_id", "event_type")) 
> DT[, sum(tot_count), by = key(DT)] 
    customer_id event_type V1 
1:   231   1 3 
2:   231   2 6 
3:   333   1 21 
4:   333   3 9 
5:   444   1 1 
6:   444   2 43 
7:   931   1 5 
8:   931   3 3