R在每年年初将累计金额重置为零 [英] R resetting a cumsum to zero at the start of each year

查看:78
本文介绍了R在每年年初将累计金额重置为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个dataframe,其中包含一堆捐赠数据.我获取数据并按时间顺序从最早到最新的礼物进行排列.接下来,我添加一列,其中包含一段时间内礼物的累计金额.该数据包含多年的数据,我一直在寻找一种在每年年初(<7年1月1日为财政年度开始和结束)将cumsum重置为0的好方法.

I have a dataframe with a bunch of donations data. I take the data and arrange it in time order from oldest to most recent gifts. Next I add a column containing a cumulative sum of the gifts over time. The data has multiple years of data and I was looking for a good way to reset the cumsum to 0 at the start of each year (the year starts and ends July 1st for fiscal purposes).

这是目前的样子:

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提供帮助的代码:

Here's the code that finally worked courtesy of 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))))

推荐答案

我会尝试这种方式(df是数据帧):

i would try it this way (df being the dataframe):

#tweak for changing the calendar year to fiscal year
df$year <- format(as.Date(df$date), format="%Y")
df$month <- format(as.Date(df$date), format="%m")
df$year <- ifelse(df$month<=6, year, year+1)

#cum-summing :)
library(plyr)
ddply(df, .(year), summarize, cumsum(giftamt))

这篇关于R在每年年初将累计金额重置为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆