[datatable-help] I have been agnozing over how to do a running cummulative sum over a particular date range
Mike.Gahan
michael.gahan at gmail.com
Tue Jul 15 04:49:22 CEST 2014
But what if the dates are irregularly spaced?
#Build some sample data
set.seed(12345)
data <- data.table(Date=seq(1,60,by=3),Value=rpois(20,10))
#Build reference table. This is where we keep the list of Dates and Values
that will be referenced for
#each individual data
Ref <- data[,list(Compare_Value=list(I(Value)),Compare_Date=list(I(Date)))]
#Use lapply to get last seven days of value by id
data[,Roll.Val := lapply(Date, function(x) {
d <- as.numeric(Ref$Compare_Date[[1]] - x)
sum((d <= 0 & d >= -7)*Ref$Compare_Value[[1]])})]
head(data,10)
Date Value Roll.Val
1: 1 12 12
2: 4 9 21
3: 7 10 31
4: 10 10 29
5: 13 14 34
6: 16 13 37
7: 19 7 34
8: 22 12 32
9: 25 12 31
10: 28 16 40
--
View this message in context: http://r.789695.n4.nabble.com/I-have-been-agnozing-over-how-to-do-a-running-cummulative-sum-over-a-particular-date-range-tp4693953p4694009.html
Sent from the datatable-help mailing list archive at Nabble.com.
More information about the datatable-help
mailing list