library(readxl)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
archivo = "C:/Examen Final/reporte.xlsx"
data <- read_excel(archivo, skip = 4)
## New names:
## • `` -> `...1`
data1 <- data %>%
  select(Código, Provincia, `No usa electricidad`, `Sí usa electricidad`, `No usa gas (balón GLP)`, `Sí usa gas (balón GLP)`, `No usa carbón`, `Sí usa carbón`, `No usa leña`, `Sí usa leña`)
head(data1)
## # A tibble: 6 × 10
##   Código Provincia                   `No usa electricidad` `Sí usa electricidad`
##   <chr>  <chr>                                       <dbl>                 <dbl>
## 1 101    Amazonas, provincia: Chach…                 14763                   574
## 2 102    Amazonas, provincia: Bagua                  20313                   161
## 3 103    Amazonas, provincia: Bonga…                  7689                   124
## 4 104    Amazonas, provincia: Condo…                  9853                    14
## 5 105    Amazonas, provincia: Luya                   13112                    90
## 6 106    Amazonas, provincia: Rodrí…                  9103                    65
## # ℹ 6 more variables: `No usa gas (balón GLP)` <dbl>,
## #   `Sí usa gas (balón GLP)` <dbl>, `No usa carbón` <dbl>,
## #   `Sí usa carbón` <dbl>, `No usa leña` <dbl>, `Sí usa leña` <dbl>
library(dplyr)
library(stringr)

data1 <- data1 %>%
  mutate(Provincia = str_extract(Provincia, "(?<=provincia: )\\w+"))

head(data1)
## # A tibble: 6 × 10
##   Código Provincia    `No usa electricidad` `Sí usa electricidad`
##   <chr>  <chr>                        <dbl>                 <dbl>
## 1 101    Chachapoyas                  14763                   574
## 2 102    Bagua                        20313                   161
## 3 103    Bongara                       7689                   124
## 4 104    Condorcanqui                  9853                    14
## 5 105    Luya                         13112                    90
## 6 106    Rodríguez                     9103                    65
## # ℹ 6 more variables: `No usa gas (balón GLP)` <dbl>,
## #   `Sí usa gas (balón GLP)` <dbl>, `No usa carbón` <dbl>,
## #   `Sí usa carbón` <dbl>, `No usa leña` <dbl>, `Sí usa leña` <dbl>
library(dplyr)

# Supongamos que data_limpia es el dataframe que tienes después de la limpieza inicial y modificación
data1 <- data1 %>%
  rowwise() %>%
  mutate(
    Total = sum(c_across(`Sí usa electricidad`:`Sí usa leña`), na.rm = TRUE),
    Porcentaje_Si_usa_electricidad = (`Sí usa electricidad` / Total) * 100,
    Porcentaje_Si_usa_GLP = (`Sí usa gas (balón GLP)` / Total) * 100,
    Porcentaje_Si_usa_carbon = (`Sí usa carbón` / Total) * 100,
    Porcentaje_Si_usa_leña = (`Sí usa leña` / Total) * 100
  ) %>%
  select(-Total)

# Ver las primeras filas del dataframe modificado
head(data1)
## # A tibble: 6 × 14
## # Rowwise: 
##   Código Provincia    `No usa electricidad` `Sí usa electricidad`
##   <chr>  <chr>                        <dbl>                 <dbl>
## 1 101    Chachapoyas                  14763                   574
## 2 102    Bagua                        20313                   161
## 3 103    Bongara                       7689                   124
## 4 104    Condorcanqui                  9853                    14
## 5 105    Luya                         13112                    90
## 6 106    Rodríguez                     9103                    65
## # ℹ 10 more variables: `No usa gas (balón GLP)` <dbl>,
## #   `Sí usa gas (balón GLP)` <dbl>, `No usa carbón` <dbl>,
## #   `Sí usa carbón` <dbl>, `No usa leña` <dbl>, `Sí usa leña` <dbl>,
## #   Porcentaje_Si_usa_electricidad <dbl>, Porcentaje_Si_usa_GLP <dbl>,
## #   Porcentaje_Si_usa_carbon <dbl>, Porcentaje_Si_usa_leña <dbl>
names(data1)
##  [1] "Código"                         "Provincia"                     
##  [3] "No usa electricidad"            "Sí usa electricidad"           
##  [5] "No usa gas (balón GLP)"         "Sí usa gas (balón GLP)"        
##  [7] "No usa carbón"                  "Sí usa carbón"                 
##  [9] "No usa leña"                    "Sí usa leña"                   
## [11] "Porcentaje_Si_usa_electricidad" "Porcentaje_Si_usa_GLP"         
## [13] "Porcentaje_Si_usa_carbon"       "Porcentaje_Si_usa_leña"
dontselect=c("Código", "Provincia", "No usa electricidad", "Sí usa electricidad", "No usa gas (balón GLP)", "Sí usa gas (balón GLP)", "No usa carbón", "Sí usa carbón", "No usa leña", "Sí usa leña")
select=setdiff(names(data1),dontselect) 
theData=data1[,select]

# usaremos:
library(magrittr)
head(theData,10)%>%
    rmarkdown::paged_table()
class(theData$Porcentaje_Si_usa_leña)
## [1] "numeric"
library(psych)
fa.parallel(theData, fa = 'fa',correct = T,plot = F)
## Parallel analysis suggests that the number of factors =  1  and the number of components =  NA
library(psych)

# Seleccionar las columnas que se usarán en el análisis factorial
data_factorial <- data1 %>%
  select(`Sí usa electricidad`, `Sí usa gas (balón GLP)`, `Sí usa carbón`, `Sí usa leña`)

# Realizar el análisis factorial
fa_result <- fa(data_factorial, nfactors = 1, rotate = "varimax") # Ajusta nfactors según sea necesario
## 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
# Ver los resultados del análisis factorial
print(fa_result)
## Factor Analysis using method =  minres
## Call: fa(r = data_factorial, nfactors = 1, rotate = "varimax")
## Standardized loadings (pattern matrix) based upon correlation matrix
##                         MR1   h2       u2 com
## Sí usa electricidad    0.95 0.91  0.08862   1
## Sí usa gas (balón GLP) 1.00 1.00 -0.00024   1
## Sí usa carbón          0.98 0.96  0.04376   1
## Sí usa leña            0.96 0.93  0.06965   1
## 
##                 MR1
## SS loadings    3.80
## Proportion Var 0.95
## 
## Mean item complexity =  1
## Test of the hypothesis that 1 factor is sufficient.
## 
## df null model =  6  with the objective function =  11.66 with Chi Square =  2295.99
## df of  the model are 2  and the objective function was  3.77 
## 
## The root mean square of the residuals (RMSR) is  0.02 
## The df corrected root mean square of the residuals is  0.04 
## 
## The harmonic n.obs is  197 with the empirical chi square  1.24  with prob <  0.54 
## The total n.obs was  200  with Likelihood Chi Square =  739.34  with prob <  2.8e-161 
## 
## Tucker Lewis Index of factoring reliability =  0.031
## RMSEA index =  1.358  and the 90 % confidence intervals are  1.28 1.445
## BIC =  728.74
## Fit based upon off diagonal values = 1
library(GPArotation)
## 
## Attaching package: 'GPArotation'
## The following objects are masked from 'package:psych':
## 
##     equamax, varimin
resfa <- fa(theData,
            nfactors = 1,
            cor = 'mixed',
            rotate = "oblimin",
            fm="minres")
print(resfa$loadings)
## 
## Loadings:
##                                MR1   
## Porcentaje_Si_usa_electricidad  0.509
## Porcentaje_Si_usa_GLP           0.903
## Porcentaje_Si_usa_carbon        0.278
## Porcentaje_Si_usa_leña         -0.965
## 
##                  MR1
## SS loadings    2.085
## Proportion Var 0.521
library(GPArotation)
resfa <- fa(theData,
            nfactors = 1,
            cor = 'mixed',
            rotate = "varimax",
            fm="minres")
print(resfa$loadings)
## 
## Loadings:
##                                MR1   
## Porcentaje_Si_usa_electricidad  0.509
## Porcentaje_Si_usa_GLP           0.903
## Porcentaje_Si_usa_carbon        0.278
## Porcentaje_Si_usa_leña         -0.965
## 
##                  MR1
## SS loadings    2.085
## Proportion Var 0.521