2017-07-17 57 views
1

我有5列的数据集:透视使用多列

store_id year event item units 
123   2015  sale_2 abc  2 
234   2015  sale_3 def  1 
345   2015  sale_2 xyz  5 

我试图通过store_id, year, and event旋转出items得到sum。例如

store_id year event abc  def xyz 
123   2015 sale_2 7  0  0 
234   2015 sale_2 2  1  0 

我很难搞清楚最好的方法。通常我会在插入符号中使用dummyVars来做到这一点,但我需要的是总和而不是标志。我已经看过tapply,但它不能处理2个以上的分组变量。

其他建议?

+0

看起来你意味着商店345为商店123代替,以便5 + 2 = 7 – C8H10N4O2

回答

3
library(reshape2) 
dcast(df, store_id + year + event ~ item, fun.aggregate = sum, value.var='units') 
# store_id year event abc def xyz 
# 1:  123 2015 sale_2 2 0 0 
# 2:  234 2015 sale_3 0 1 0 
# 3:  345 2015 sale_2 0 0 5 

对于大型数据集考虑

# uses dcast.data.table, much faster 
library(data.table) 
setDT(df) 
dcast(df, store_id + year + event ~ item, fun.aggregate = sum, value.var='units') 
2
library(dplyr) 
library(tidyr) 
data %>% 
group_by(store_id, year, event, item) %>% 
summarize(N = sum(units)) %>% 
spread(item, N) 

您可以使用dplyr分组总结,tidyr的数据传播到所需的项目列。