yottalab
yottalab

Reputation: 76

R - Rolling balance function

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

Please, could you help me with this challenge in R? I have got a dataframe with columns DATE, C, PAYMENT and TRX_AMNT. I want to create a function(in this case two - one inside) to create column ROLLING based on the note next to.

Thank you for help.

Upvotes: 0

Views: 114

Answers (1)

yottalab
yottalab

Reputation: 76

Solved. ;) (tx, for hint with 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

Upvotes: 1

Related Questions