我有下面的数据框,并且想要为每个月添加一列QT += multimedia
来计算接下来3个月SumNextMonths
的总和。
例如:
2月份的SumNextMonths = Mar + Apr + May的SalesForecasts。
SalesForecasts
有人知道如何继续吗?
谢谢你, 干杯
答案 0 :(得分:0)
一般答案可能是:
library(dplyr)
library(zoo)
d %>%
mutate(temp_lead = lead(SalesForecasts, n = 1),
SalesforNext3Months = rollapply(data = temp_lead,
width = 3,
FUN = sum,
align = "left",
fill = NA,
na.rm = T))%>%
select(-temp_lead)
Period SalesForecasts SalesforNext3Months
1 Jan 100 400
2 Feb 100 600
3 Mar 200 700
4 Apr 100 700
5 May 300 500
6 Jun 300 400