0

Is there a way to apply a function to the n column values above within each group? I would like to calculate the standard deviation of the 24 values above and I'm looking for a function like the lag operator but this lag should be applied to 24 lags (at once).

data <- mutate(data, vola = sd(lag(return,1:24)))

Is there an appropriate dplyr function? thanks in advance

FlowRyan
  • 205
  • 1
  • 3
  • 7
  • Please show a small reproducible example and expected output – akrun Jun 05 '16 at 14:46
  • 3
    It seems crazy to me that you are using the `return` as a variable name. With that being said, `lag` function from `dplyr` does not support multiple lags at the same time. You can borrow the `shift` from `data.table` package and use it as `shift(return, 1:24, type = "lag")`. – Psidom Jun 05 '16 at 14:47
  • (1) Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. (2) You might be looking for the the `rollapply` function from the `zoo` package or the `roll_sd` function from the `RcppRoll` package. – Jaap Jun 05 '16 at 14:52

0 Answers0