【发布时间】:2011-12-16 15:43:42
【问题描述】:
我有一个dataframe,里面有一堆捐款数据。我把数据从最旧的到最近的礼物按时间顺序排列。接下来,我添加一列,其中包含随着时间的推移累积的礼物总和。该数据包含多年的数据,我一直在寻找一种在每年年初将cumsum 重置为 0 的好方法(出于财务目的,该年从 7 月 1 日开始和结束)。
目前是这样的:
id date giftamt cumsum()
005 01-05-2001 20.00 20.00
007 06-05-2001 25.00 45.00
009 12-05-2001 20.00 65.00
012 02-05-2002 30.00 95.00
015 08-05-2002 50.00 145.00
025 12-05-2002 25.00 170.00
... ... ... ...
这是我想要的样子:
id date giftamt cumsum()
005 01-05-2001 20.00 20.00
007 06-05-2001 25.00 45.00
009 12-05-2001 20.00 20.00
012 02-05-2002 30.00 50.00
015 08-05-2002 50.00 50.00
025 12-05-2002 25.00 75.00
... ... ... ...
有什么建议吗?
更新:
这是最终由 Seb 提供的代码:
#tweak for changing the calendar year to fiscal year
df$year <- as.numeric(format(as.Date(df$giftdate), format="%Y"))
df$month <- as.numeric(format(as.Date(df$giftdate), format="%m"))
df$year <- ifelse(df$month<=6, df$year, df$year+1)
#cum-summing :)
library(plyr)
finalDf <- ddply(df, .(year), summarize, cumsum(as.numeric(as.character(giftamt))))
【问题讨论】:
-
您的示例输出是否应该有所不同,或者您是否希望总和在 2001 年 5 月 12 日重置?
-
重置日期为 7 月 1 日。抱歉数据稀疏。
-
我在最初的回答中对此进行了监督 - 抱歉。我的新尝试现在应该可以了。我认为...