Is there a better way to compute the average of the 3 previous time periods (or N time periods) to compute a function (mean, sum, etc.) using lead or lag?
data_final <- data_final %>%
group_by(cars) %>%
mutate(last3_average = (lag(speed, 1) + lag(speed, 2) + lag(speed, 3))/3)
I used the zoo package as suggested below:
data_final <- data_final %>%
group_by(cars) %>%
mutate(last3_average = lag(rollmean(speed, 3, na.pad = T, align = "right"), 1))