Chapter 13 Stan for Bayesian time series analysis

For this lab, we will use Stan for fitting models. These examples are primarily drawn from the Stan manual and previous code from this class.

A script with all the R code in the chapter can be downloaded here. The Rmd for this chapter can be downloaded here

Data and packages

You will need the atsar and bayesdfa packages we have written for fitting state-space time series models with Stan. Install using the devtools package.

library(devtools)
# Windows users will likely need to set this
# Sys.setenv('R_REMOTES_NO_ERRORS_FROM_WARNINGS' = 'true')
devtools::install_github("nwfsc-timeseries/atsar")
devtools::install_github("nwfsc-timeseries/tvvarss")
devtools::install_github("fate-ewi/bayesdfa")

In addition, you will need the rstan, datasets, parallel and loo packages. After installing, if needed, load the packages:

library(atsar)
library(rstan)
library(loo)

Once you have Stan and rstan installed, optimize Stan on your machine:

rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())

For this lab, we will use a data set on air quality in New York from the datasets package. Load the data and create a couple new variables for future use.

data(airquality, package = "datasets")
Wind <- airquality$Wind  # wind speed
Temp <- airquality$Temp  # air temperature