Reputation: 92
I am trying to perform this operation within an xts object, but I am obtaining an error. The libraries and data used are:
#Libraries
library(xts)
library(dynlm)
#Data
index <- seq.Date(from = Sys.Date() - 999, to = Sys.Date(), by = "days")
x <- xts(1:1000, order.by = index)
y <- xts(2001:3000, order.by = index)
z <- xts(3001:4000, order.by = index)
data <- merge(x,y,z)
And I am trying to perform this dynamic regression
dynlm(x ~ L(y) + L(z,4), data = data)
Any thoughts? Or should I just convert the information as a dataframe and work from there. Thanks in advance!
Upvotes: 0
Views: 424
Reputation: 269852
One way to proceed is to use the dyn package. (Be sure that dplyr is NOT loaded since dplyr overwrites lag
with its own version that is incompatible with the rest of R.)
library(dyn)
dyn$lm(x ~ lag(y) + lag(z, 4), data = data)
giving:
Call:
lm(formula = dyn(x ~ lag(y) + lag(z, 4)), data = data)
Coefficients:
(Intercept) lag(y) lag(z, 4)
-1999 1 NA
Upvotes: 1
Reputation: 92
It appears that dynlm does not work well with 'xts' objects.
One solution given by Grothendieck suggests using a different package (which works).
Another solution is to change the object to zoo.
Nevertheless, this was confusing as the object I was working initially was class: "xts" "zoo"; and dynlm was not recognizing the 'zoo' part.
After changing it to 'zoo' everything works if somebody wants to stay with this package.
#Libraries
library(xts)
library(dynlm)
#Data
index <- seq.Date(from = Sys.Date() - 999, to = Sys.Date(), by = "days")
x <- xts(1:1000, order.by = index)
y <- xts(2001:3000, order.by = index)
z <- xts(3001:4000, order.by = index)
data <- merge(x,y,z)
data.zoo <- zoo(data, order.by = index(data))
dynlm(x ~ L(y) + L(z,4), data = data.zoo)
Giving
Time series regression with "zoo" data:
Start = 2017-05-23, End = 2020-02-12
Call:
dynlm(formula = x ~ L(y) + L(z, 4), data = data.zoo)
Coefficients:
(Intercept) L(y) L(z, 4)
-1999 1 NA
Curiosly, the intercept obtained is different.
Upvotes: 0