I have the following dataframe in R. I'm trying to calculate a 5 day rolling Z score (X minus its rolling mean, divided by its rolling standard deviation) by creating a function for this using rollify
)
library(tibbletime)
library(tidyverse)
rolling_Z <- rollify(~((.x - mean(.x))/sd(.x)), window = 5)
data <- structure(list(Date = structure(c(19282, 19283, 19284, 19285,
19286, 19289, 19290, 19291, 19292, 19293, 19296, 19297, 19298,
19299, 19300, 19303), class = "Date"), `US 10 Year` = c(3.824,
3.881, 3.881, 3.947, 3.943, 4.018, 4.01, 4.007, 4.134, 4.228,
4.217, 4.242, 4.102, 4.003, 3.919, 3.998)), row.names = c(NA,
-16L), class = c("tbl_df", "tbl", "data.frame"))
data %>%
mutate(Z_Score = rolling_Z(`US 10 Year`))
However I'm getting the following error. I'm guessing it is because US 10 Year
is not the same length as the rolling mean and rolling standard deviation seeing as the first four days would be an NA. Is there a way to overcome this issue?
Error in `mutate()`:
! Problem while computing `Z_Score = rolling_Z(`US 10 Year`)`.
x `Z_Score` must be size 16 or 1, not 64.
So I'm not sure how tibbletime works but you can use the
zoo
package which has multipleroll
functions.You didn't specify whether you wanted a forward roll or a roll that took from both sides so in this case I used
rollapplyr()
There are parameters in the zoo
roll()
function family that allow you to specify how you want to roll, whether you should allow partials, etc. and you can change these to fit your needs.If you wanted to make this into a function you could also do this.