另一种方法是使用rollapply
from zoo 包。
使用与 Ben Bolker 的数据略有不同的数据并应用rollapply
您可以得到它。
set.seed(1)
var <- data.frame(matrix(runif(10000),nrow=1000))
colnames(var) <- c("y", paste0("x", 1:9))
Coef <- rollapply(var,
width = 100, by=100,
FUN = function(z) {
coef(lm(y~., data=as.data.frame(z)))
},
by.column = FALSE, align = "right")
round(Coef, 3) # and here's the coefficients corresponding to the 10 regressions
(Intercept) x1 x2 x3 x4 x5 x6 x7 x8 x9
[1,] 0.416 -0.253 0.093 -0.047 0.039 0.081 0.053 -0.022 0.084 0.006
[2,] 0.656 0.144 -0.209 -0.150 -0.066 0.084 0.018 -0.114 -0.016 0.073
[3,] 0.311 -0.134 0.006 0.047 0.036 0.020 0.082 0.172 0.211 -0.090
[4,] 0.720 -0.110 0.094 -0.058 -0.018 -0.256 -0.058 0.074 -0.042 0.010
[5,] 0.510 0.052 0.019 -0.193 -0.045 0.114 -0.093 0.044 0.059 0.051
[6,] 1.044 -0.037 -0.300 -0.180 0.148 0.018 -0.187 -0.128 -0.182 -0.154
[7,] 0.558 0.027 -0.231 -0.074 0.065 0.192 -0.022 -0.105 -0.002 0.046
[8,] 0.496 0.156 -0.129 -0.061 0.025 0.028 -0.010 0.097 -0.031 -0.090
[9,] 0.435 0.140 0.138 -0.170 -0.085 -0.069 -0.077 -0.056 0.190 0.105
[10,] 0.282 0.078 0.014 -0.005 0.110 0.149 0.001 0.175 -0.017 -0.033