---
title: "Fisher example"
author: "kmg"
date: "2/7/2019"
output:
  word_document: default
  html_document: default
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Prepare environment

```{r, echo = TRUE}
library(lavaan)
library(semPlot)

load("~/Dropbox/Classes/IAV/Data/Fisher/FisherData.Rdata")
```

## Get data ready. 
```{r, echo = TRUE}
data <- FisherDataInterp[[7]] # used person number 7
data_lag <- FisherDataInterp[[7]][1:114,]
data_lag[,27:52] <- FisherDataInterp[[7]][2:115,]
names1 <- colnames(data_lag[,1:26])
colnames(data_lag) <- c(names1, paste0(names1, "C"))

```
## Run PFA model

```{r, echo = TRUE}
  model <- paste("FA1~FA2_lag", "FA1~FA1_lag", "FA2~FA2_lag", # VAR
                  "FA1~~FA1", "FA2 ~~ FA2",                # variance of LVs
                  "FA1 ~~ 0*FA2",                          # constraints 
                  sep = "\n")

  # measurement models:   
  FA1 <- "FA1 =~ 1*avoid_actC + l1*avoid_peopleC + l2*concentrateC + l3*hopelessC"
  FA2 <- "FA2 =~ 1*enthusiasticC + l4*contentC + l5*positiveC + l6*acceptedC"
  
  FA1_lag <- "FA1_lag =~ avoid_act + l1*avoid_people + l2*concentrate + l3*hopeless"
  FA2_lag <- "FA2_lag =~ enthusiastic + l4*content + l5*positive + l6*accepted"

  # Notice that lambdas are constrained to be equal with the "l#" indicators.
  
  # Paste it all together. 
  model_full <- paste(model, FA1, FA2, FA1_lag, FA2_lag, sep = "\n")
  

  fit_all <- lavaan::sem(model_full, as.data.frame(data_lag)) 
```

## Plot results.

You can also embed plots, for example:

```{r pressure, echo=TRUE}
semPaths(fit_all)
```

## Examine estimates. 
Let's take a look at the measurement model parameters. 
```{r, echo = TRUE}
measurement <- parameterEstimates(fit_all)[parameterEstimates(fit_all)$op %in% c("=~"),1:8 ]

print(measurement)
```


Let's take a look at the structural model parameters. 
```{r, echo = TRUE}
structural <- parameterEstimates(fit_all)[parameterEstimates(fit_all)$op %in% c("~"), 1:8]

print(structural)
```

## Take a look at fit. 
```{r, echo = TRUE}
fitMeasures(fit_all, c("cfi","rmsea","srmr"))
```
