![](/img/trans.png)
[英]Aggregate values in data frame based on an array of start and end dates - R
[英]sum/aggregate data based on dates, R
我有一個如下數據集:
Date Country Item Qty Value
15-04-2014 SE 08888 2 20
28-04-2014 SE 08888 2 20
05-05-2014 SE 08888 6 80
我想在日期為5月1日之前對數量值求和,並且合計值(總和)應標記為5月1日。
我嘗試了ddply
,但是無論日期如何,它都會對所有值求和。
ddply(se, .(se$Item), summarize, Qty = sum(se$Qty), Value = sum(se$Value))
還嘗試按日期進行子集化,但沒有大的成功。
se$Date <- as.Date(as.character(se$Date))
se_q <- subset(se,se$Date <= 01-05-2014)
Date Country Item Qty Value
0015-04-20 SE 08888 2 20
0028-04-20 SE 08888 2 20
0005-05-20 SE 08888 6 80
如何在代碼中添加date參數? 或我該怎么做?
謝謝
您可以使用dplyr
例如:
require(dplyr)
> df %.%
filter(Date <= as.Date("2014-05-01")) %.%
# group_by(Item) %.% #you can add this line if you need to group by Item (it will appear in the output then)
summarize(Date = as.Date("2014-05-01"), Qty = sum(Qty), Value = sum(Value))
# Date Qty Value
#1 2014-05-01 4 40
您的subset
的問題是您沒有告訴R 2014-05-01
是一個Date
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.