library(tidyr)
library(corrplot)
corrplot 0.92 loaded
library(psych)
library(ggplot2)

Attaching package: ‘ggplot2’

The following objects are masked from ‘package:psych’:

    %+%, alpha
#https://stats.oarc.ucla.edu/spss/seminars/efa-spss/
#https://www.karlin.mff.cuni.cz/~maciak/NMST539/cvicenie8.html

fullData <- read.csv("https://raw.githubusercontent.com/PrisonRodeo/PLSC504-2023-git/main/Exercises/PLSC504-2023-ExerciseSeven.csv")
fullData <- drop_na(fullData)

data <- fullData[, 5:13]

corrplot(cor(data), method = "ellipse")

fa.parallel(data)
Warning: The estimated weights for the factor scores are probably incorrect.  Try a different factor score estimation method.
Parallel analysis suggests that the number of factors =  1  and the number of components =  1 

The variables are highly related as shown by the uniqueness and the correlation plot.


fa1 <- factanal(data, factors = 1, scores = "regression", rotation = "none")
print(fa1)

Call:
factanal(x = data, factors = 1, scores = "regression", rotation = "none")

Uniquenesses:
  xrreg  xrcomp  xropen  xconst  parreg parcomp   exrec exconst polcomp 
  0.006   0.005   0.007   0.007   0.011   0.005   0.013   0.007   0.022 

Loadings:
        Factor1
xrreg   0.997  
xrcomp  0.999  
xropen  0.996  
xconst  0.996  
parreg  0.995  
parcomp 0.998  
exrec   0.994  
exconst 0.996  
polcomp 0.989  

               Factor1
SS loadings      8.920
Proportion Var   0.991

Test of the hypothesis that 1 factor is sufficient.
The chi square statistic is 270447.7 on 27 degrees of freedom.
The p-value is 0 
loadings <- fa1$loadings
corr <- cor(data)[ , 1]

plot(loadings, corr)
abline(a = 0, b = 1, lwd = 2)

The loadings are highly correlated and the uniqueness of the variables is very low, suggesting that each variable measures a similar construct.


scores <- fa1$scores[1:196, ]
subsetted <- subset(fullData, country == "Afghanistan")

ggplot(data = subsetted, mapping = (aes(x = year, y = polity2))) +
    geom_line() + 
    geom_line(aes(y = scores, color = "Red"))

This plot specifically looks at the first country in the dataset– Afghanistan. This plot shows that there is heavy correlation between the factor scores and the polity2 variable. Specifically, in 1970 the polity score increases drastically as the factor scores decrease drastically. This again happens in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