Why does the rollapply function in R returns a matrix when applied to a vector?

173 views Asked by At

I have a tibble of daily financial data. Similar to the below:

head(df)

tibble [2,871 x 2] (S3: tbl_df/tbl/data.frame)
Price | Volatility
15.4    17.5
14.7    17.8
14.4    17.7
14.9    17.8
...     ...

I have written a function to calculate z-scores:

zscore <- function(x) {
  z <- (x-mean(x))/sd(x)
  return(z)
}

I want to add two additional columns, 1) which calculates each row's z-score, and another that calculates the rolling z-scores over a period of 255 business days (i.e. approx. 1 calendar year)

I've written the below code which returns an error message:

df %>%
  mutate(full_zscore = zscore(Volatility),
         roll_zscore = rollapply(Volatility, 255, FUN = zscore, align = "right"))

Error: Invalid index: out of bounds

Upon further investigation I noticed that the rollapply function returns a matrix and hence why i get the error message.

Can anyone help me understand why the rollapply(df$Volatility, 255, FUN = zscore, alighn = "right") returns a matrix rather than a rolling z-score on the new variable column?

Thanks!

0

There are 0 answers