---
title: "Confirmatory Factor Analysis and SEM"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(message = FALSE)
knitr::opts_chunk$set(warning = FALSE) #to supress warning messages in all output
```
```{r}
library(mosaic)
library(ggplot2)
library(dplyr)
library(psych)
library(lavaan)
library(semPlot)
```
#Confirmatory Factor Analysis
Now, instead of taking a shot in the dark about the factor structure, we are going in with a clear idea about which items we things load on which factors. Our goal is to test how well our model of the factor structure actually fits the data.
First we specify the model.
```{r}
bf_model <- ' agreeable =~ A1 + A2 + A3 + A4 + A5
conscient =~ C1 + C2 + C3 + C4 + C5
extrov =~ E1 + E2 + E3 + E4 + E5
neurot =~ N1 + N2 + N3 + N4 + N5
openness =~ O1 + O2 + O3 + O4 + O5 '
```
##Diagram
Plot the model to make sure it is what you want. Here we are using the `semPaths()` and `semPlotModel()` from the `semPlot` package. The `rotation = 2` option forces the exogenous variables to be on the left side.
```{r}
semPaths(semPlotModel(bf_model), rotation = 2)
```
##Output
Then fit the CFA model with `cfa()` and ask for the relevant output.
```{r}
bf_fit <- cfa(bf_model, data = bfi)
summary(bf_fit, rsq=TRUE)
inspect(bf_fit, what = "std") #for standardized estimates
```
##Re-specifying the Model
Maybe we want to add error covariances based on modification indices. I recommend only doing this if it makes theoretical sense. Also, what ever theoretical rule you use to justify making these error correlations, if it applies to other sets of items, then add the correlations there too. Be consistent! **If you just make changes based on the modification indicies without thinking carefully about the theory behind them, then you are doing exploratory factor analysis.**
```{r}
bf_model_re1 <- ' agreeable =~ A1 + A2 + A3 + A4 + A5
conscient =~ C1 + C2 + C3 + C4 + C5
extrov =~ E1 + E2 + E3 + E4 + E5
neurot =~ N1 + N2 + N3 + N4 + N5
openness =~ O1 + O2 + O3 + O4 + O5
N1 ~~ N2
N3 ~~ N4'
bf_model_re1.1 <- ' agreeable =~ A1 + A2 + A3 + A4 + A5
conscient =~ C1 + C2 + C3 + C4 + C5
extrov =~ E1 + E2 + E3 + E4 + E5
anx =~ N1 + N2
dep =~ N3 + N4
neurot =~ anx + dep + N5
openness =~ O1 + O2 + O3 + O4 + O5 '
```
How would you ask for a diagram of this model?
```{r}
semPaths(semPlotModel(bf_model_re1.1), rotation = 2)
```
```{r}
bf_fit_re1 <- cfa(bf_model_re1, data = bfi)
summary(bf_fit_re1, rsq=TRUE)
inspect(bf_fit_re1, what = "std")
```
We might also want to remove A1 -- "Am indifferent to the feelings of others," and O4 -- "Spend time reflecting on things," based on crappy loadings.
```{r}
bf_model_re2 <- ' agreeable =~ A2 + A3 + A4 + A5
conscient =~ C1 + C2 + C3 + C4 + C5
extrov =~ E1 + E2 + E3 + E4 + E5
neurot =~ N1 + N2 + N3 + N4 + N5
openness =~ O1 + O2 + O3 + O5
N1 ~~ N2
N3 ~~ N4'
bf_fit_re2 <- cfa(bf_model_re2, data = bfi)
summary(bf_fit_re2, rsq=TRUE)
inspect(bf_fit_re2, what = "std")
```