sum - R previous week total -
this question has answer here:
- aggregate week in r 1 answer
i have date (column b) , total (column a) variables - how can create new variable in r sums previous 7 days' worth of totals?
in excel, have following formula:
=sumifs($a:$a,$b:$b, ">="&$b20-7,$b:$b,"<"&$b20)
and don't know how convert work in r. suggestions?
if there 1 total per day, function may help:
rollsums <- function(totals, roll) { res <- c() for(i in 1:(length(totals)-roll)) { res <- c(res, sum(totals[0:(roll-1)+i])) } res } df1 total date 1 3 2015-01-01 2 8 2015-01-01 3 4 2015-01-02 4 7 2015-01-03 5 6 2015-01-04 6 1 2015-01-04 7 10 2015-01-05 8 9 2015-01-06 9 2 2015-01-07 10 5 2015-01-08 rollsums(df1$total, 3) [1] 15 19 17 14 17 20 21 rollsums(df1$total, 4) [1] 22 25 18 24 26 22
it take 2 arguments, vector totals , how many days you'd in each sum.
data
dput(df1) structure(list(total = c(3l, 8l, 4l, 7l, 6l, 1l, 10l, 9l, 2l, 5l), date = structure(c(16436, 16436, 16437, 16438, 16439, 16439, 16440, 16441, 16442, 16443), class = "date")), .names = c("total", "date"), row.names = c(na, -10l), class = "data.frame")
update
in case run situation multiple values on same day, here's solution. surprisingly, @mikewise has one-liner can of this. see other answer.
grouped.roll <- function(df, values, group, roll) { totals <- eval(substitute(with(df, tapply(values, group, sum)))) newsums <- rollsums(totals, roll) data.frame(group=names(totals), sums=c(rep(na, roll), newsums)) }
it uses rollsums
used earlier. spit out nas until desired day grouping begins. may advantage on other answer. edit in, i'm sure. providing more options reference.
grouped.roll(df1, total, date, 3) group sums 1 2015-01-01 na 2 2015-01-02 na 3 2015-01-03 na 4 2015-01-04 22 5 2015-01-05 18 6 2015-01-06 24 7 2015-01-07 26 8 2015-01-08 21
Comments
Post a Comment