我想在 r 中构建一个固定的滚动窗口。假设我有一个这样的数据集:
Apple Microsoft Amazon Tesla
2000 0.91903890 0.5454254 0.22267026 0.41857974
2001 0.13638076 0.7640585 0.56990815 0.04490846
2002 0.19977390 0.9170585 0.04391331 0.72987722
2003 0.70627675 0.2583974 0.03485766 0.35594681
2004 0.08069703 0.2085965 0.19865918 0.30194120
2005 0.03334810 0.7955248 0.75876036 0.28129544
2006 0.94652374 0.6095904 0.98855677 0.36792881
2007 0.90060660 0.3144541 0.78201742 0.02731390
我知道以下功能会给我一个扩展窗口:
all.cov.matrix <- lapply(1:nrow(stocks), function(y) cov(stocks[1:y,]))
为了获得一个内部有四个句点的固定窗口,我尝试了以下功能:
library(zoo)
all.cov.matrix <- apply(rollapply(1:nrow(stocks), 4, c), 1, function(ix) cov(stocks[ix, ]))
# However, this returns one big matrix, that is not what I am looking for.
# Ideally I want to get the following results:
cov(stocks[1:4,]) # 1 period
cov(stocks[2:5,]) # 2 period and so on
我希望将每个矩阵单独存储在 中all.cov.matrix
,因此在 thix 示例中all.cov.matrix
应该存储 5 个不同的矩阵。