问题描述
我想使用 lm 对单个动物园对象内的多对数据系列执行滚动回归.
I would like to perform a rolling regression using lm on many pairs of data series within a single zoo object.
虽然我能够通过以下代码对动物园对象中的一对数据系列执行滚动回归:
While I am able to perform a rolling regression on one single pair of data series in a zoo object by the following codes:
FunLm <- function(x,Param,Days) coef(lm(AAA ~ Z, data = as.data.frame(x), weights=Param*(seq(Days,1,by=-1))))
DataLmCoef <- rollapplyr(Data, Days, FunLm, Param, Days, by.column = FALSE)
具有这种结构的动物园:
with zoo of this structure:
Z AAA
2012-07-01 1 853
2012-07-04 2 864
2012-07-05 3 865
2012-07-06 4 873
2012-07-07 5 870
2012-07-08 6 874
我的问题是,如果我有以下动物园对象:
My question is, if I have the following zoo object:
Z AAA BBB CCC
2012-07-01 1 853 123 65
2012-07-04 2 864 124 62
2012-07-05 3 865 126 63
2012-07-06 4 873 120 66
2012-07-07 5 870 121 68
2012-07-08 6 874 123 69
不使用循环,如何在 Z~AAA、Z~BBB、Z~CCC、Z~DDD.... 上执行类似的滚动回归,并获得两个动物园矩阵对象,一个存储截距,另一个存储斜率?
without using loop, how can I perform rolling regression similarly on Z~AAA, Z~BBB, Z~CCC, Z~DDD, .... and get two zoo matrix objects with one storing intercepts and the other storing slopes?
推荐答案
遵循 rollapply
中的示例 手册页
您可以在滚动功能中添加多个测试例如
You can add more then one test in the roll function for example
> seat <- as.zoo(log(UKDriverDeaths))
> time(seat) <- as.yearmon(time(seat))
> seat <- merge(y = seat, y1 = lag(seat, k = -1),
y12 = lag(seat, k = -12), all = FALSE)
> fm <- rollapply(seat, width = 36,
FUN = function(z)
data.frame(
test1 = t(coef(lm(y ~ y1 + y12, data = as.data.frame(z)))),
test3 = t(coef(lm(y ~ y12, data = as.data.frame(z))))
) ,
by.column = FALSE, align = "right")
结果
> head(fm)
test1..Intercept. test1.y1 test1.y12 test3..Intercept. test3.y12
דצמ 1972 0.9629793 0.15344243 0.7240740 1.530598 0.8026003
ינו 1973 1.1336058 0.13920023 0.7155899 1.570067 0.7973688
פבר 1973 0.9978077 0.14346100 0.7293183 1.440635 0.8145803
מרץ 1973 0.9879002 0.12929214 0.7442218 1.375245 0.8226257
אפר 1973 1.2281307 0.11700612 0.7250115 1.545356 0.8003661
מאי 1973 1.4483700 0.08860055 0.7245032 1.706343 0.7792279
这篇关于R:在动物园矩阵对象上滚动应用 lm 回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!