Reputation: 21
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
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?
Upvotes: 2
Views: 2586
Reputation: 9789
Following the example from the rollapply
man page
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")
And the result
> 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
Upvotes: 3