DATE C PAYMENT TRX_AMNT ROLLING (note)
01/01/2014 1 30 2 28 first row in cycle (PAYMENT - TRX_AMNT)
01/01/2014 1 15 13 previous ROLLING-TRX_AMNT+PAYMENT
01/01/2014 1 17 -4 previous ROLLING-TRX_AMNT+PAYMENT
02/01/2014 1 10 2 4 previous ROLLING-TRX_AMNT+PAYMENT
02/01/2014 1 20 -16 previous ROLLING-TRX_AMNT+PAYMENT
03/01/2014 1 15 5 -6 previous ROLLING-TRX_AMNT+PAYMENT
04/01/2014 1 50 30 14 previous ROLLING-TRX_AMNT+PAYMENT
05/01/2014 2 15 10 5 first row in cycle (PAYMENT - TRX_AMNT)
05/01/2014 2 2 3 previous ROLLING-TRX_AMNT+PAYMENT
拜托,你能帮我解决一下这个挑战吗?我有一个包含DATE,C,PAYMENT和TRX_AMNT列的数据框。我想创建一个函数(在这种情况下是两个 - 一个内部),根据旁边的注释创建列ROLLING。
感谢您的帮助。
答案 0 :(得分:1)
解决。 ;)(tx,用于提示与cumsum)
library(data.table)
dat1<-read.table(text="
id, x, date
1, 5, 2012-06-05 12:01
1, 10, 2012-06-05 12:02
1, 45, 2012-06-05 12:03
2, 5, 2012-06-05 12:01
2, 3, 2012-06-05 12:03
2, 2, 2012-06-05 12:05
3, 5, 2012-06-05 12:03
3, 5, 2012-06-05 12:04
3, 8, 2012-06-05 12:05
1, 5, 2012-06-08 13:01
1, 9, 2012-06-08 13:02
1, 3, 2012-06-08 13:03
2, 0, 2012-06-08 13:15
2, 1, 2012-06-08 13:18
2, 8, 2012-06-08 13:20
2, 4, 2012-06-08 13:21
3, 6, 2012-06-08 13:15
3, 2, 2012-06-08 13:16
3, 7, 2012-06-08 13:17
3, 2, 2012-06-08 13:18
",sep=",",header=TRUE,stringsAsFactors=FALSE)
dat1
dat1$date<-as.Date(dat1$date,format="%Y-%m-%d %H:%M")
dat1
dat2<-dat1[order(dat1[,1],dat1[,3]),]
dat2
dat2$acc1<-ave(dat2$x,FUN=cumsum)
dat2$acc2<-ave(dat2$x,list(dat2$id),FUN=cumsum)
dat2$acc3<-ave(dat2$x,list(dat2$id,dat2$date),FUN=cumsum)
dat2