I would like to generate covariance matrices (and mean vectors) using a rolling window. But in all my attempts rollapply
stacks the covariance matrices from cov
and runs out of pre-allocated space (e.g., if my original data have 40 observations, then rollapply
can't return more than 40 rows).
Is there a way that I can get rollapply
to return a list of matrices? Or to return a data.frame
that is larger than the original data.frame
, which I can manually split into a list? My end goal is to take a panel, split the panel into a list of individual data.frame
s, calculate the rolling covariances and means for each data frame, then use these lists of covariances and means downstream to compare to a bunch of individuals.
Here is some code. My problem is that my.fun
won't return data from all covariance matrix caluclations. Is my best option to code my own rollapply
? Or my own cov
that returns a vector that I convert back to a matrix? Thanks!
library("zoo")
data.df <- data.frame(sic = rep(1:10, each = 40),
year = rep(1:40, len = 10*40),
one = rnorm(10*40),
two = 2*rnorm(10*40),
three = 3*rnorm(10*40))
data.list <- split(data.df, data.df$sic)
data.list <- lapply(data.list, zoo)
my.fun <- function(x) {
x <- x[, c("one", "two", "three")]
rollapply(x,
width = 10,
FUN = cov,
by.column = F,
align = "right")
}
cov.list <- lapply(data.list, FUN = my.fun)