library(dynlm)
## Warning: package 'dynlm' was built under R version 3.6.2
library(car) 
library(sandwich)
library(knitr)
library(broom)
library(readxl)
######################################
data<-read_excel("D:/My projects/ex9_2.xlsx")
attach(data)
head(data)
## # A tibble: 6 x 2
##   sales   adv
##   <dbl> <dbl>
## 1  37.8  1.6 
## 2  39.2  1.67
## 3  39.2  1.73
## 4  39.0  1.59
## 5  38.7  1.71
## 6  36.7  1.77
check.ts<-is.ts(data)
sales.ts<-ts(data,start=c(1998,1),end=c(2006,9),frequency = 12)
plot(sales.ts[,"sales"],ylab="Sales")

plot(sales.ts[,"adv"],ylab="Advertisement revenue")

sales1.dyn=dynlm(sales~L(adv,0:2),data=sales.ts)
kable(tidy(summary(sales1.dyn)), digits=4,
      caption="The distributed lag model with three lags")
The distributed lag model with three lags
term estimate std.error statistic p.value
(Intercept) 25.3435 1.5999 15.8403 0.0000
L(adv, 0:2)0 1.8418 1.1809 1.5596 0.1220
L(adv, 0:2)1 3.8016 1.4699 2.5863 0.0112
L(adv, 0:2)2 2.2655 1.1922 1.9002 0.0603
ehat <- resid(sales1.dyn)
corrgm <- acf(ehat)

sales2.dyn=dynlm(sales~lag(sales,-1)+lag(adv,0)+lag(adv,-1)+lag(adv,-2),data=sales.ts)
kable(tidy(summary(sales2.dyn)), digits=4,
      caption="The distributed lag model with three lags")
The distributed lag model with three lags
term estimate std.error statistic p.value
(Intercept) 27.6089 3.0818 8.9588 0.0000
lag(sales, -1) -0.0851 0.0989 -0.8605 0.3916
lag(adv, 0) 1.8547 1.1826 1.5683 0.1200
lag(adv, -1) 3.9377 1.4803 2.6601 0.0091
lag(adv, -2) 2.7215 1.3061 2.0836 0.0398
dhat <- resid(sales2.dyn)

model=c("first","second")
glL3 <- glance(sales1.dyn)[c("r.squared","statistic","AIC","BIC")]
glL2 <- glance(sales2.dyn)[c("r.squared","statistic","AIC","BIC")]
table <- rbind(glL3, as.numeric(glL2))
table=cbind(model,table)
kable(table, caption="Goodness-of-fit")
Goodness-of-fit
model r.squared statistic AIC BIC
first 0.4000894 22.00819 387.9270 401.1006
second 0.4045882 16.64799 389.1516 404.9600