我有一个数据框 dat
关于二手车卖家的汽车销售(数据框中的 Buy=0
)和购买(数据框中的 Buy=1
)。
Date Buy Price
29-06-2015 1 5000
29-06-2015 0 8000
29-06-2015 1 10000
30-06-2015 0 3500
30-06-2015 0 12000
... ... ...
我需要的是一个新的聚合 data.frame,它为我提供每天的买入和卖出数量以及当天所有买入和卖出的总价格:
Date Buys Sells Price_Buys Price_Sells
29-06-2015 2 1 15000 8000
30-06-2015 0 2 0 15500
... ... ...
我尝试使用
aggregate(dat$Buy, by=list(Date=dat$Date, FUN=sum))
.但是,我仍然在努力如何汇总销售量。
最佳答案
这可以在 dplyr
中非常干净地完成。 , 按日期分组使用 group_by
然后用 summarize
总结:
library(dplyr)
(out <- dat %>%
group_by(Date) %>%
summarize(Buys=sum(Buy == 1), Sells=sum(Buy == 0),
Price_Buys=sum(Price[Buy == 1]), Price_Sells=sum(Price[Buy == 0])))
# Date Buys Sells Price_Buys Price_Sells
# (fctr) (int) (int) (int) (int)
# 1 29-06-2015 2 1 15000 8000
# 2 30-06-2015 0 2 0 15500
您现在可以像操作普通数据框一样操作此对象,例如像这样:
out$newvar <- with(out, Sells*Price_Sells - Buys*Price_Buys)
out
# Source: local data frame [2 x 6]
# Date Buys Sells Price_Buys Price_Sells newvar
# (fctr) (int) (int) (int) (int) (int)
# 1 29-06-2015 2 1 15000 8000 -22000
# 2 30-06-2015 0 2 0 15500 31000
关于r - 每天聚合 data.frame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35071953/