##Limpieza y jalar datos

library(rio)
demo = import("demo.csv", encoding = "UTF-8")
idh = import("idh2.csv", encoding = "UTF-8")
demo[,]=lapply(demo[,], trimws,whitespace = "[\\h\\v]")
idh[,]=lapply(idh[,], trimws,whitespace = "[\\h\\v]")
str(demo)
## 'data.frame':    167 obs. of  9 variables:
##  $ Puesto                       : chr  "1" "2" "3" "4" ...
##  $ País                         : chr  "Noruega" "Nueva Zelanda" "Finlandia" "Suecia" ...
##  $ Puntuación                   : chr  "9,75" "9,37" "9,27" "9,26" ...
##  $ Proceso electoraly pluralismo: chr  "10,00" "10,00" "10,00" "9,58" ...
##  $ Funcionamientodel gobierno   : chr  "9,64" "8,93" "9,29" "9,29" ...
##  $ Participaciónpolítica        : chr  "10,00" "9,44" "8,89" "8,33" ...
##  $ Culturapolítica              : chr  "10,00" "8,75" "8,75" "10,00" ...
##  $ Derechosciviles              : chr  "9,12" "9,71" "9,41" "9,12" ...
##  $ Categoría                    : chr  "Democracia plena" "Democracia plena" "Democracia plena" "Democracia plena" ...
names(idh)
## [1] "País >> IDH Muy Alto >> IDH Alto >> IDH Medio >> IDH Bajo"                                                                                    
## [2] "Componentes para Indice de Desarrollo Humano >> Esperanza de Vida (85 años) >> IDH Muy Alto >> IDH Alto >> IDH Medio >> IDH Bajo"             
## [3] "Componentes para Indice de Desarrollo Humano >> Años Esperados de Escolaridad ( 18 años) >> IDH Muy Alto >> IDH Alto >> IDH Medio >> IDH Bajo"
## [4] "Componentes para Indice de Desarrollo Humano >> Años Promedio de Escolaridad (15 años) >> IDH Muy Alto >> IDH Alto >> IDH Medio >> IDH Bajo"  
## [5] "Componentes para Indice de Desarrollo Humano >> PIB per capita PPP (2017) (75,000) >> IDH Muy Alto >> IDH Alto >> IDH Medio >> IDH Bajo"
names(demo)
## [1] "Puesto"                        "País"                         
## [3] "Puntuación"                    "Proceso electoraly pluralismo"
## [5] "Funcionamientodel gobierno"    "Participaciónpolítica"        
## [7] "Culturapolítica"               "Derechosciviles"              
## [9] "Categoría"
colnames(idh)[1] = "Pais"
colnames(idh)[2] = "EsperanzaVida"
colnames(idh)[3] = "EscolaridadDuracion"
colnames(idh)[4] = "EscolaridadPromedio"
colnames(idh)[5] = "PBI"
names(idh)
## [1] "Pais"                "EsperanzaVida"       "EscolaridadDuracion"
## [4] "EscolaridadPromedio" "PBI"
library(stringr)
names(demo)=str_to_title(names(demo))
library(stringi)
names(demo)=gsub(" ","",names(demo))
names(demo)=stri_trans_general(str = names(demo), 
                               id = "Latin-ASCII")
idh[,]=lapply(idh[,], trimws,whitespace = "[\\h\\v]") 

demo[,]=lapply(demo[,], trimws,whitespace = "[\\h\\v]")
names(demo)
## [1] "Puesto"                      "Pais"                       
## [3] "Puntuacion"                  "ProcesoElectoralyPluralismo"
## [5] "FuncionamientodelGobierno"   "Participacionpolitica"      
## [7] "Culturapolitica"             "Derechosciviles"            
## [9] "Categoria"
names(idh)
## [1] "Pais"                "EsperanzaVida"       "EscolaridadDuracion"
## [4] "EscolaridadPromedio" "PBI"
str(demo)
## 'data.frame':    167 obs. of  9 variables:
##  $ Puesto                     : chr  "1" "2" "3" "4" ...
##  $ Pais                       : chr  "Noruega" "Nueva Zelanda" "Finlandia" "Suecia" ...
##  $ Puntuacion                 : chr  "9,75" "9,37" "9,27" "9,26" ...
##  $ ProcesoElectoralyPluralismo: chr  "10,00" "10,00" "10,00" "9,58" ...
##  $ FuncionamientodelGobierno  : chr  "9,64" "8,93" "9,29" "9,29" ...
##  $ Participacionpolitica      : chr  "10,00" "9,44" "8,89" "8,33" ...
##  $ Culturapolitica            : chr  "10,00" "8,75" "8,75" "10,00" ...
##  $ Derechosciviles            : chr  "9,12" "9,71" "9,41" "9,12" ...
##  $ Categoria                  : chr  "Democracia plena" "Democracia plena" "Democracia plena" "Democracia plena" ...
str(idh)
## 'data.frame':    191 obs. of  5 variables:
##  $ Pais               : chr  "Suiza" "Noruega" "Islandia" "Hong Kong" ...
##  $ EsperanzaVida      : chr  "84" "83.2" "82.7" "85.5" ...
##  $ EscolaridadDuracion: chr  "16.5" "18.2" "19.2" "17.3" ...
##  $ EscolaridadPromedio: chr  "13.9" "13" "13.8" "12.2" ...
##  $ PBI                : chr  "66,933" "64,660" "55,782" "62,607" ...
idh$PBI=gsub(',','',idh$PBI)
idh[,-1]=lapply(idh[,-1], as.numeric)
## Warning in lapply(idh[, -1], as.numeric): NAs introducidos por coerción
str(idh)
## 'data.frame':    191 obs. of  5 variables:
##  $ Pais               : chr  "Suiza" "Noruega" "Islandia" "Hong Kong" ...
##  $ EsperanzaVida      : num  84 83.2 82.7 85.5 84.5 81.4 83 82 80.6 81.7 ...
##  $ EscolaridadDuracion: num  16.5 18.2 19.2 17.3 21.1 18.7 19.4 18.9 17 18.7 ...
##  $ EscolaridadPromedio: num  13.9 13 13.8 12.2 12.7 13 12.6 11.6 14.1 12.6 ...
##  $ PBI                : num  66933 64660 55782 62607 49238 ...
demo[,-c(2,9)]=lapply(demo[,-c(2,9)],
                      function(x){gsub(",",".",x)})
demo[,-c(2,9)]=lapply(demo[,-c(2,9)], as.numeric)
str(demo)
## 'data.frame':    167 obs. of  9 variables:
##  $ Puesto                     : num  1 2 3 4 5 6 7 8 9 9 ...
##  $ Pais                       : chr  "Noruega" "Nueva Zelanda" "Finlandia" "Suecia" ...
##  $ Puntuacion                 : num  9.75 9.37 9.27 9.26 9.18 9.09 9 8.99 8.9 8.9 ...
##  $ ProcesoElectoralyPluralismo: num  10 10 10 9.58 10 10 10 10 10 9.58 ...
##  $ FuncionamientodelGobierno  : num  9.64 8.93 9.29 9.29 8.21 8.93 7.86 9.64 8.57 8.93 ...
##  $ Participacionpolitica      : num  10 9.44 8.89 8.33 8.89 8.33 8.33 7.78 7.78 7.78 ...
##  $ Culturapolitica            : num  10 8.75 8.75 10 9.38 9.38 9.38 8.13 8.75 9.38 ...
##  $ Derechosciviles            : num  9.12 9.71 9.41 9.12 9.41 8.82 9.41 9.41 9.41 8.82 ...
##  $ Categoria                  : chr  "Democracia plena" "Democracia plena" "Democracia plena" "Democracia plena" ...
idh[!complete.cases(idh),]
##        Pais EsperanzaVida EscolaridadDuracion EscolaridadPromedio  PBI
## 151 Camerún          60.3                  NA                 6.2 3621
demo[!complete.cases(demo),]
## [1] Puesto                      Pais                       
## [3] Puntuacion                  ProcesoElectoralyPluralismo
## [5] FuncionamientodelGobierno   Participacionpolitica      
## [7] Culturapolitica             Derechosciviles            
## [9] Categoria                  
## <0 rows> (or 0-length row.names)
idh=idh[complete.cases(idh),]
demo=demo[complete.cases(demo),]
idh$Pais=stri_trans_general(str = idh$Pais, 
                               id = "Latin-ASCII")

demo[,c(2,9)]=lapply(demo[,c(2,9)],
                     stri_trans_general,
                     id = "Latin-ASCII") 
setdiff(demo$Pais,idh$Pais)
## [1] "Republica de China" ""                   "Suazilandia"       
## [4] "Camerun"            "Rd del Congo"       "Corea del Norte"
setdiff(idh$Pais,demo$Pais)
##  [1] "Liechtenstein"                   "Andorra"                        
##  [3] "San Marino"                      "Brunei Darusalam"               
##  [5] "Bahamas"                         "Panama"                         
##  [7] "Granada"                         "Barbados"                       
##  [9] "Antigua y Barbuda"               "Seychelles"                     
## [11] "San Cristobal y Nieves"          "Palaos"                         
## [13] "San Vicente y las Granadinas"    "Maldivas"                       
## [15] "Tonga"                           "Dominica"                       
## [17] "Santa Lucia"                     "Palestina"                      
## [19] "Samoa"                           "Belice"                         
## [21] "Tuvalu"                          "Islas Marshall"                 
## [23] "Micronesia"                      "Kiribati"                       
## [25] "Santo Tome y Principe"           "Vanuatu"                        
## [27] "Esuatini"                        "Islas Salomon"                  
## [29] "Pakistan"                        "Republica Democratica del Congo"
## [31] "Sudan del Sur"

##Merge

control3=merge(idh,demo)
str(control3)
## 'data.frame':    159 obs. of  13 variables:
##  $ Pais                       : chr  "Afganistan" "Albania" "Alemania" "Angola" ...
##  $ EsperanzaVida              : num  62 76.5 80.6 61.6 76.9 76.4 75.4 72 84.5 81.6 ...
##  $ EscolaridadDuracion        : num  10.3 14.4 17 12.2 16.1 14.6 17.9 13.1 21.1 16 ...
##  $ EscolaridadPromedio        : num  3 11.3 14.1 5.4 11.3 8.1 11.1 11.3 12.7 12.3 ...
##  $ PBI                        : num  1824 14131 54534 5466 46112 ...
##  $ Puesto                     : num  167 68 15 122 152 113 50 89 9 20 ...
##  $ Puntuacion                 : num  0.32 6.11 8.67 3.37 2.08 3.77 6.81 5.49 8.9 8.07 ...
##  $ ProcesoElectoralyPluralismo: num  0 7 9.58 1.33 0 3.08 9.17 7.5 10 9.58 ...
##  $ FuncionamientodelGobierno  : num  0.07 6.43 8.21 2.86 3.57 2.5 5 5.71 8.57 6.79 ...
##  $ Participacionpolitica      : num  0 4.44 8.33 5 2.22 4.44 7.22 6.11 7.78 8.89 ...
##  $ Culturapolitica            : num  1.25 5.63 8.13 5 3.13 5 5 3.13 8.75 6.88 ...
##  $ Derechosciviles            : num  0.29 7.06 9.12 2.65 1.47 3.82 7.65 5 9.41 8.24 ...
##  $ Categoria                  : chr  "Regimen autoritario" "Democracia deficiente" "Democracia plena" "Regimen autoritario" ...
dontselect=c("Pais","Puesto","Puntuacion",'Categoria')
select=setdiff(names(control3),dontselect) 
theData=control3[,select]

###Análisis factorial exploratorio (EFA) ##Matriz de correlación

library(polycor)
library(ggcorrplot)
## Loading required package: ggplot2
corMatrix=polycor::hetcor(theData)$correlations
ggcorrplot(corMatrix)

##¿Se pueden factorizar?

library(psych)
## 
## Attaching package: 'psych'
## The following objects are masked from 'package:ggplot2':
## 
##     %+%, alpha
## The following object is masked from 'package:polycor':
## 
##     polyserial
psych::KMO(corMatrix) 
## Kaiser-Meyer-Olkin factor adequacy
## Call: psych::KMO(r = corMatrix)
## Overall MSA =  0.9
## MSA for each item = 
##               EsperanzaVida         EscolaridadDuracion 
##                        0.90                        0.90 
##         EscolaridadPromedio                         PBI 
##                        0.90                        0.89 
## ProcesoElectoralyPluralismo   FuncionamientodelGobierno 
##                        0.83                        0.95 
##       Participacionpolitica             Culturapolitica 
##                        0.95                        0.88 
##             Derechosciviles 
##                        0.86

##¿La matriz de correlación es adecuada? Pruebas para saberlo

library(matrixcalc)
cortest.bartlett(corMatrix,n=nrow(theData))$p.value>0.05
## [1] FALSE
is.singular.matrix(corMatrix)
## [1] FALSE

##¿Cuántos factores se pueden tener?

fa.parallel(theData, fa = 'fa',correct = T,plot = F)
## Warning in fa.stats(r = r, f = f, phi = phi, n.obs = n.obs, np.obs = np.obs, :
## The estimated weights for the factor scores are probably incorrect. Try a
## different factor score estimation method.
## Warning in fac(r = r, nfactors = nfactors, n.obs = n.obs, rotate = rotate, : An
## ultra-Heywood case was detected. Examine the results carefully
## Warning in fa.stats(r = r, f = f, phi = phi, n.obs = n.obs, np.obs = np.obs, :
## The estimated weights for the factor scores are probably incorrect. Try a
## different factor score estimation method.

## Warning in fa.stats(r = r, f = f, phi = phi, n.obs = n.obs, np.obs = np.obs, :
## The estimated weights for the factor scores are probably incorrect. Try a
## different factor score estimation method.

## Warning in fa.stats(r = r, f = f, phi = phi, n.obs = n.obs, np.obs = np.obs, :
## The estimated weights for the factor scores are probably incorrect. Try a
## different factor score estimation method.

## Warning in fa.stats(r = r, f = f, phi = phi, n.obs = n.obs, np.obs = np.obs, :
## The estimated weights for the factor scores are probably incorrect. Try a
## different factor score estimation method.
## Warning in fac(r = r, nfactors = nfactors, n.obs = n.obs, rotate = rotate, : An
## ultra-Heywood case was detected. Examine the results carefully
## Warning in fa.stats(r = r, f = f, phi = phi, n.obs = n.obs, np.obs = np.obs, :
## 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 =  2  and the number of components =  NA

##Redimensionar a los factores que nos sugiere

library(GPArotation)
resfa <- fa(theData,
            nfactors = 2,
            cor = 'mixed',
            rotate = "varimax",
            fm="minres")
print(resfa$loadings)
## 
## Loadings:
##                             MR1   MR2  
## EsperanzaVida               0.278 0.868
## EscolaridadDuracion         0.392 0.816
## EscolaridadPromedio         0.300 0.792
## PBI                         0.290 0.804
## ProcesoElectoralyPluralismo 0.909 0.228
## FuncionamientodelGobierno   0.762 0.492
## Participacionpolitica       0.776 0.333
## Culturapolitica             0.524 0.401
## Derechosciviles             0.909 0.319
## 
##                  MR1   MR2
## SS loadings    3.516 3.360
## Proportion Var 0.391 0.373
## Cumulative Var 0.391 0.764
print(resfa$loadings,cutoff = 0.5)
## 
## Loadings:
##                             MR1   MR2  
## EsperanzaVida                     0.868
## EscolaridadDuracion               0.816
## EscolaridadPromedio               0.792
## PBI                               0.804
## ProcesoElectoralyPluralismo 0.909      
## FuncionamientodelGobierno   0.762      
## Participacionpolitica       0.776      
## Culturapolitica             0.524      
## Derechosciviles             0.909      
## 
##                  MR1   MR2
## SS loadings    3.516 3.360
## Proportion Var 0.391 0.373
## Cumulative Var 0.391 0.764

##Gráfico de las variables ya redimensionadas

fa.diagram(resfa,main = "Resultados del EFA")

##¿Qué variable aportó más?

sort(resfa$communality)
##             Culturapolitica       Participacionpolitica 
##                   0.4354346                   0.7130596 
##         EscolaridadPromedio                         PBI 
##                   0.7165864                   0.7313910 
##         EscolaridadDuracion   FuncionamientodelGobierno 
##                   0.8204914                   0.8221573 
##               EsperanzaVida ProcesoElectoralyPluralismo 
##                   0.8298232                   0.8787391 
##             Derechosciviles 
##                   0.9286240

##¿Qué variables contribuyeron a más de un factor?

sort(resfa$complexity)
## ProcesoElectoralyPluralismo               EsperanzaVida 
##                    1.125234                    1.202724 
##             Derechosciviles                         PBI 
##                    1.242485                    1.256253 
##         EscolaridadPromedio       Participacionpolitica 
##                    1.280643                    1.356853 
##         EscolaridadDuracion   FuncionamientodelGobierno 
##                    1.438349                    1.710639 
##             Culturapolitica 
##                    1.870422

Dos índices que resuman los valores encontrados

library(magrittr)
as.data.frame(resfa$scores)%>%head()
##          MR1        MR2
## 1 -1.7791494 -0.8633563
## 2  0.3172115  0.2849561
## 3  1.0373841  1.1681259
## 4 -0.7575112 -0.6720571
## 5 -1.9986785  1.5867070
## 6 -0.8755320  0.4176185

##Gráficos

control3$demos_efa=resfa$scores[,1]
control3$desahu_efa=resfa$scores[,2]

ggplot(data=control3,aes(x=Puntuacion,y=demos_efa)) + geom_point() + theme_minimal() + labs(x="Indice de Democracia (original)", y="Indice de Democracia EFA")

library(BBmisc)
## 
## Attaching package: 'BBmisc'
## The following object is masked from 'package:base':
## 
##     isFALSE
efa_scores_ok=normalize(resfa$scores, 
                       method = "range", 
                       margin=2, # by column
                       range = c(0, 10))

control3$demos_efa_ok=efa_scores_ok[,1]
control3$desahu_efa_ok=efa_scores_ok[,2]

ggplot(data=control3,aes(x=Puntuacion,y=demos_efa_ok)) + geom_point() + theme_minimal() + labs(x="Indice de Democracia (original)", y="Indice de Democracia EFA (cambiado)")

###Análisis factorial confirmatorio (CFA)

modelCFA <- ' democracia  =~ ProcesoElectoralyPluralismo + FuncionamientodelGobierno + Participacionpolitica + Culturapolitica + Derechosciviles

desaHumano=~EsperanzaVida+EscolaridadDuracion+EscolaridadPromedio+PBI'
theDataNorm=scale(theData)
library(lavaan)
## This is lavaan 0.6-12
## lavaan is FREE software! Please report any bugs.
## 
## Attaching package: 'lavaan'
## The following object is masked from 'package:psych':
## 
##     cor2cov
cfa_fit <- cfa(modelCFA, data=theDataNorm, 
           std.lv=TRUE,  
           missing="fiml")
summary(cfa_fit)
## lavaan 0.6-12 ended normally after 30 iterations
## 
##   Estimator                                         ML
##   Optimization method                           NLMINB
##   Number of model parameters                        28
## 
##   Number of observations                           159
##   Number of missing patterns                         1
## 
## Model Test User Model:
##                                                       
##   Test statistic                               122.450
##   Degrees of freedom                                26
##   P-value (Chi-square)                           0.000
## 
## Parameter Estimates:
## 
##   Standard errors                             Standard
##   Information                                 Observed
##   Observed information based on                Hessian
## 
## Latent Variables:
##                    Estimate  Std.Err  z-value  P(>|z|)
##   democracia =~                                       
##     PrcsElctrlyPlr    0.927    0.060   15.466    0.000
##     FuncnmntdlGbrn    0.880    0.062   14.090    0.000
##     Participcnpltc    0.836    0.064   12.991    0.000
##     Culturapolitic    0.637    0.072    8.894    0.000
##     Derechoscivils    0.961    0.058   16.467    0.000
##   desaHumano =~                                       
##     EsperanzaVida     0.891    0.063   14.250    0.000
##     EscolariddDrcn    0.920    0.061   15.053    0.000
##     EscolariddPrmd    0.868    0.063   13.672    0.000
##     PBI               0.823    0.066   12.520    0.000
## 
## Covariances:
##                    Estimate  Std.Err  z-value  P(>|z|)
##   democracia ~~                                       
##     desaHumano        0.673    0.048   13.946    0.000
## 
## Intercepts:
##                    Estimate  Std.Err  z-value  P(>|z|)
##    .PrcsElctrlyPlr   -0.000    0.079   -0.000    1.000
##    .FuncnmntdlGbrn   -0.000    0.079   -0.000    1.000
##    .Participcnpltc    0.000    0.079    0.000    1.000
##    .Culturapolitic    0.000    0.079    0.000    1.000
##    .Derechoscivils    0.000    0.079    0.000    1.000
##    .EsperanzaVida     0.000    0.079    0.000    1.000
##    .EscolariddDrcn   -0.000    0.079   -0.000    1.000
##    .EscolariddPrmd   -0.000    0.079   -0.000    1.000
##    .PBI              -0.000    0.079   -0.000    1.000
##     democracia        0.000                           
##     desaHumano        0.000                           
## 
## Variances:
##                    Estimate  Std.Err  z-value  P(>|z|)
##    .PrcsElctrlyPlr    0.134    0.020    6.676    0.000
##    .FuncnmntdlGbrn    0.220    0.029    7.459    0.000
##    .Participcnpltc    0.294    0.037    7.995    0.000
##    .Culturapolitic    0.587    0.068    8.651    0.000
##    .Derechoscivils    0.071    0.016    4.356    0.000
##    .EsperanzaVida     0.200    0.032    6.349    0.000
##    .EscolariddDrcn    0.148    0.028    5.330    0.000
##    .EscolariddPrmd    0.241    0.034    7.066    0.000
##    .PBI               0.317    0.042    7.458    0.000
##     democracia        1.000                           
##     desaHumano        1.000

##¿Qué tan bien salió el modelo?

allParamCFA=parameterEstimates(cfa_fit,standardized = T)
allFitCFA=as.list(fitMeasures(cfa_fit))

##ChiSquare - pvalue debe ser mayor a 0.05

allFitCFA[c("chisq", "df", "pvalue")]
## $chisq
## [1] 122.4497
## 
## $df
## [1] 26
## 
## $pvalue
## [1] 1.84297e-14

##Índice de Tucker Lewis - debe ser mayor a 0.9

allFitCFA$tli
## [1] 0.9063776

##La raíz del error cuadrático medio de aproximación debe ser menor a 0.05

allFitCFA[c('rmsea.ci.lower','rmsea' ,'rmsea.ci.upper')] 
## $rmsea.ci.lower
## [1] 0.1260951
## 
## $rmsea
## [1] 0.1527444
## 
## $rmsea.ci.upper
## [1] 0.1805155

##Aunque no se cumpla a cabalidad, igual se calculan las puntuaciones

scorescfa=normalize(lavPredict(cfa_fit),
                    method = "range", 
                    margin=2, # by column
                    range = c(0, 10))

control3$demos_cfa_ok=scorescfa[,1]
control3$desahu_cfa_ok=scorescfa[,2]
ggplot(data=control3,aes(x=Puntuacion,y=demos_cfa_ok)) + geom_point() + theme_minimal() + labs(x="Indice de Democracia (original)", y="Indice de Democracia CFA (cambiado)")

##Resultados del CFA

library(lavaanPlot)
lavaanPlot(model = cfa_fit, node_options = list(shape = "box", fontname = "Helvetica"), edge_options = list(color = "grey"), coefs = T)

##Regresión normal

hipotesis=formula(demos_cfa_ok~desahu_cfa_ok)
reg1=lm(hipotesis, data=control3)
summary(reg1)
## 
## Call:
## lm(formula = hipotesis, data = control3)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -5.098 -1.188  0.575  1.208  3.484 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept)     1.5856     0.3488   4.546 1.09e-05 ***
## desahu_cfa_ok   0.7655     0.0616  12.428  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.911 on 157 degrees of freedom
## Multiple R-squared:  0.4959, Adjusted R-squared:  0.4927 
## F-statistic: 154.4 on 1 and 157 DF,  p-value: < 2.2e-16
modelSEM <- ' democracia  =~ ProcesoElectoralyPluralismo + FuncionamientodelGobierno + Participacionpolitica + Culturapolitica + Derechosciviles

desaHumano=~EsperanzaVida+EscolaridadDuracion+EscolaridadPromedio+PBI

democracia~desaHumano'
sem_fit <- sem(modelSEM, 
              data=theDataNorm)
summary(sem_fit)
## lavaan 0.6-12 ended normally after 32 iterations
## 
##   Estimator                                         ML
##   Optimization method                           NLMINB
##   Number of model parameters                        19
## 
##   Number of observations                           159
## 
## Model Test User Model:
##                                                       
##   Test statistic                               122.450
##   Degrees of freedom                                26
##   P-value (Chi-square)                           0.000
## 
## Parameter Estimates:
## 
##   Standard errors                             Standard
##   Information                                 Expected
##   Information saturated (h1) model          Structured
## 
## Latent Variables:
##                    Estimate  Std.Err  z-value  P(>|z|)
##   democracia =~                                       
##     PrcsElctrlyPlr    1.000                           
##     FuncnmntdlGbrn    0.949    0.051   18.502    0.000
##     Participcnpltc    0.902    0.056   16.196    0.000
##     Culturapolitic    0.687    0.070    9.762    0.000
##     Derechoscivils    1.036    0.042   24.599    0.000
##   desaHumano =~                                       
##     EsperanzaVida     1.000                           
##     EscolariddDrcn    1.033    0.058   17.897    0.000
##     EscolariddPrmd    0.974    0.062   15.783    0.000
##     PBI               0.924    0.065   14.167    0.000
## 
## Regressions:
##                    Estimate  Std.Err  z-value  P(>|z|)
##   democracia ~                                        
##     desaHumano        0.701    0.074    9.410    0.000
## 
## Variances:
##                    Estimate  Std.Err  z-value  P(>|z|)
##    .PrcsElctrlyPlr    0.134    0.021    6.462    0.000
##    .FuncnmntdlGbrn    0.220    0.029    7.662    0.000
##    .Participcnpltc    0.294    0.036    8.090    0.000
##    .Culturapolitic    0.587    0.068    8.683    0.000
##    .Derechoscivils    0.071    0.016    4.318    0.000
##    .EsperanzaVida     0.200    0.031    6.528    0.000
##    .EscolariddDrcn    0.148    0.027    5.496    0.000
##    .EscolariddPrmd    0.241    0.034    7.061    0.000
##    .PBI               0.317    0.041    7.665    0.000
##    .democracia        0.470    0.065    7.229    0.000
##     desaHumano        0.794    0.111    7.140    0.000

##Resultado en gráfico

lavaanPlot(model = sem_fit,
           node_options = list(shape = "box",
                               fontname = "Helvetica"),
           edge_options = list(color = "grey"), coefs = T,stand = T)

##Mismo resultado pero otro gráfico

library(semPlot)
semPaths(sem_fit, residuals=F,
         sizeMan=7,sizeLat=12,
         what = "std",
         nCharNodes=10,
         posCol=c("skyblue4", "red"),
         edge.color="orange",
         edge.label.cex=1.2,layout="circle2")