I'm trying to generate an "up-to-x-months" rolling average that resets after missing data. In other words, the rolling period should vary based on how many of the contiguously preceding months have available data, up to a limit of x months for the lookback period.
I tried using cumsum and a lag, but I couldn't figure out how to do a variable lag.
Any advice on a good approach for this? Perhaps this is doable with zoo or tidyquant?
library(tidyverse)
max_lookback_mo <- 3 # This will be 12 in real use, using 3 for simpler example.
# I have month and total, and would like to calculate the other two columns.
monthly_data <- tribble(
~month, ~total, ~desired_mos_incl, ~desired_avg,
1, 100, 1, 100,
2, 200, 2, 150,
3, NA, NA, NA,
4, 200, 1, 200,
5, 300, 2, 250,
6, 400, 3, 300,
7, 500, 3, 400,
8, 420, 3, 440
)