R 上周总计 [英] R previous week total
问题描述
我有日期(B 列)和总计(A 列)变量 - 如何在 R 中创建一个新变量来汇总前 7 天的总计值?
I have Date (column B) and Total (column A) variables - how can I create a new variable in R that sums the previous seven days' worth of Totals?
在 Excel 中,我有以下公式:
In Excel, I have the following formula:
=SUMIFS($A:$A,$B:$B, ">="&$B20-7,$B:$B,"<"&$B20)代码>
我只是不知道如何将其转换为在 R 中工作.建议?
and I just don't know how to convert this to work in R. Suggestions?
推荐答案
这也可以,高级但简短 - 本质上是单行的.
This will do it too, advanced, but short - essentially a one-liner.
# Initialze some data
date <- seq(as.Date("2001-01-01"),as.Date("2001-01-31"),"days")
tot <- trunc(rnorm(31,100,20))
df <- data.frame(date,tot)
# Now compute week sum by summing a subsetted df for each date
df$wktot <- sapply(df$date,function(x)sum(df[difftime(df$date,x,,"days") %in% 0:-6,]$tot))
更改变量名称以匹配提出的问题.
Changed the variable names to match the posed problem.
它还可以按任意顺序处理数据,每天处理多个条目.
It also handles the data in any order and multiple entries per day.
编辑以添加评论并使其适合窗口.
Edited to add comments and make it fit in a window.
这篇关于R 上周总计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!