Problem fitting a regression to time series with trending package

114 views Asked by At

I am trying to fit a negative binomial regression to a time series using the trending package. When I try to calculate the confidence intervals and prediction intervals, I get the error message:

Error in cbind(): ! Not supported for tsibble. ℹ Please use dplyr::bind_cols() instead.

Can someone please help?

Thanks

library(surveillance)
library(tidyverse)
library(tsibble)
library(forecast)
library(trending)

data(campyDE)

countsdf <- campyDE%>%
  select(date, case)

countsdf$date <- as.Date(countsdf$date)

countsdf <- countsdf %>% 
  mutate(epiweek = yearweek(date, week_start = 1))

countsdf <- tsibble(countsdf, index = epiweek) 

countsdf$fourier <- select(countsdf, epiweek, case) %>% 
  fourier(K = 1)

head(countsdf)

model <- glm_nb_model(
  case ~
    epiweek +
    fourier)

fitted_model <- trending::fit(model, countsdf)

observed <- predict(fitted_model, simulate_pi = FALSE)

1

There are 1 answers

0
Rob Hyndman On

The problem is you are mixing multiple packages that are not designed to work together, and eventually that causes a clash. In particular, the tsibble package is designed to work with fable for modelling, not with trending or with forecast.

The only part of the code that relies on tsibble here is in the creation of epiweek using yearweek(), and in obtaining the weekly frequency of the data inside fourier(). The only part that relies on forecast is in the creation of the Fourier terms.

Here is a modification of your code that avoids the problems by not creating a tsibble object, and computing the two fourier columns directly, rather than via the forecast::fourier() function.

library(surveillance)
#> Loading required package: sp
#> Loading required package: xtable
#> This is surveillance 1.20.0. For overview type 'help(surveillance)'.
library(tidyverse)
library(trending)

data(campyDE)

countsdf <- campyDE%>%
  select(date, case) %>% 
  mutate(
    epiweek = tsibble::yearweek(date, week_start = 1),
    fourier1 = sin(2*pi*seq(NROW(campyDE))/52.18),
    fourier2 = cos(2*pi*seq(NROW(campyDE))/52.18)
  )

model <- glm_nb_model(case ~ epiweek + fourier1 + fourier2)

fitted_model <- trending::fit(model, countsdf)

observed <- predict(fitted_model, simulate_pi = FALSE)

Created on 2022-04-27 by the reprex package (v2.0.1)