Carbo
Carbo

Reputation: 916

Autoregressive model with panel data in r

I have the following dataset dt

Y     date       segment
 10   2019-11-11    1
 12   2019-11-12    1
 9    2019-11-13    1
 ...
 ..
 14   2019-12-15    5
 12   2019-12-16    5
 10   2019-12-17    5

I want to build an autoregressive model such that

 Y(segment, dat)_{t} = beta1*Y(segment,dat)_{t-1} + beta2*Y(segment,dat)_{t-2}...

while I have to problems with just one segment as I would do something like this:

library(dynlm)
Y <- dt$Y
AR2 <- dynlm(ts(Y) ~ L(ts(Y)) + L(ts(Y), 2) )

I am not sure how to do with multiple segments at the same time

Upvotes: 1

Views: 482

Answers (1)

Rob Hyndman
Rob Hyndman

Reputation: 31800

The simplest approach is to use lm() like this:

library(tidyverse)
dt <- tibble(
  Y = sample(1:50, 200, replace=TRUE),
  date = rep(seq(as.Date("2019-11-11"), by="1 day", length=40),5),
  segment = rep(1:5, rep(40, 5))
)

dt <- dt %>%
  arrange(segment, date) %>%
  group_by(segment) %>%
  mutate(
    Y1 = dplyr::lag(Y,1),
    Y2 = dplyr::lag(Y,2)
  ) %>%
  ungroup()

fit <- lm(Y ~ Y1 + Y2, data=dt)

Created on 2020-08-27 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions