--- title: "VAR Fisher example Chapter 4" author: "Kathleen M. Gates" output: word_document: default pdf_document: default html_document: default --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` Set up the environment: ```{r} library(vars) library(signal) ``` ## Prepare data Start by selecting one individual and a handful of variables. ```{r} load("~/Dropbox/Classes/IAV/Data/Fisher/FisherData.Rdata") # The list 'FisherDataInterp' contains the interpolated data for all individuals. # Select a few variables from the first person. datasub <- cbind(FisherDataInterp[[1]]$angry, FisherDataInterp[[1]]$irritable, FisherDataInterp[[1]]$anhedonia) # scale and give names colnames(datasub) <- c("angry", "irritable", "anhedonia") datasub <- scale(datasub, center = TRUE, scale = TRUE) # plot the data plot(ts(datasub[,1])) plot(ts(datasub[,2])) plot(ts(datasub[,3])) ``` ## Test for trends ```{r} time <- seq(1:length(datasub[,1])) # create time vector coeffs <- NULL # test for linear trend across the selected variables for (p in 1: length(datasub[1,])){ fit<- lm(datasub[,p] ~ time) #run a simple regression predicting time coeffs[p] <- fit$coefficients[2] } max(coeffs) # the max coefficient here is zero with rounding # linear trends not seen ``` ## Test the univariate order. ```{r} ar(datasub[,1]) ar(datasub[,2]) ar(datasub[,3]) ``` The first variable (anger) appears to have an AR(4) process, whereas the others are AR(1). We can test for the VAR order, which will tell us how many lags to include for our multivariate investigations. Note that sometimes this will be smaller than one of the variables univariate order. ## Test VAR order ```{r} # test a lag of max 5 fitVAR <- VAR(datasub, lag.max = 5, ic = c("AIC")) fitVAR$p coef(fitVAR) ``` The oiptimal lag order was found to be 2, for a VAR(2) process. We see that $angry$ has a positive AR(1) coefficient and a negative AR(2) coefficient. $angry$ also has a positive lag-1 relation with $irritable$. $irritable$ is predicted by itself at a prior lag, and $anhedonia$ at a lag of two. Both are positive relations. Finally, $anhedonia$ has lag-1 positive relations with itself and $angry$. ## Obtain covariance matrix ```{r} ccf(datasub[,2], datasub[,1], plot = FALSE) ccf(datasub[,1], datasub[,2], plot = FALSE) ``` Notice that order matters here. Visualizations help to identify patterns. ```{r} ccf(datasub[,2], datasub[,1], plot = TRUE) ```