0

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))
panstotts
  • 623
  • 1
  • 5
  • 13
  • yes, is there a better way to automate this if you had say 100 time periods? – panstotts Oct 20 '15 at 21:32
  • It is possible my data was setup different but incorporating rollmean and lag did the trick: `mutate(last3_avg = lag(rollmean(speed, 3, na.pad = T, align = "right"), 1))` – panstotts Oct 20 '15 at 22:09

0 Answers0