1. Introducción

Column {data-width= 700}

Column {data-width= 300}

Hipótesis

A nivel departamental, el porcentaje de alfabetismo está afectado por el porcentaje de personas nativas que asisten actualmente a un centro educativo, la cantidad de lenguas nativas habladas, el porcentaje de personas que hablan lenguas nativas, el porcentaje de población femenina, el porcentaje de personas que viven en el área rural, el porcentaje de personas que sufren una discapacidad motora, el porcentaje de personas que sufren una discapacidad intelectual y el porcentaje de hogares que tienen acceso a internet.

2. Variable central

Column {data-width=500}

Histograma del porcentaje de alfabetización

Boxplot

Column {data-width=500}

Tabla de frecuencias

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  41.30   85.30   89.50   87.68   93.90   97.80 

3. Correlación (VD vs VIs)

Column {data-width=750}

N°lenguas nativas

% lenguas nativas

Población femenina

Población rural

Discapacidad motora

Discapacidad intelectual

Acceso a internet

Instituciones bilingues

Column {data-width=250}

N°lenguas nativas


    Spearman's rank correlation rho

data:  data$p_alfabetizacion and data$c_lenguas
S = 2456.6, p-value = 0.7934
alternative hypothesis: true rho is not equal to 0
sample estimates:
       rho 
0.05516898 

% lenguas nativas


    Spearman's rank correlation rho

data:  data$p_alfabetizacion and data$p_lenguasnativas
S = 4112, p-value = 0.002295
alternative hypothesis: true rho is not equal to 0
sample estimates:
       rho 
-0.5815526 

Población femenina


    Spearman's rank correlation rho

data:  data$p_alfabetizacion and data$p_mujer
S = 3676.5, p-value = 0.03964
alternative hypothesis: true rho is not equal to 0
sample estimates:
       rho 
-0.4140192 

Población rural


    Spearman's rank correlation rho

data:  data$p_alfabetizacion and data$p_rural
S = 4783.9, p-value = 1.508e-07
alternative hypothesis: true rho is not equal to 0
sample estimates:
       rho 
-0.8399777 

Discapacidad motora


    Spearman's rank correlation rho

data:  data$p_alfabetizacion and data$p_motora
S = 2299.6, p-value = 0.5823
alternative hypothesis: true rho is not equal to 0
sample estimates:
      rho 
0.1155403 

Discapacidad intelectual


    Spearman's rank correlation rho

data:  data$p_alfabetizacion and data$p_intelectual
S = 2804.3, p-value = 0.7089
alternative hypothesis: true rho is not equal to 0
sample estimates:
        rho 
-0.07856737 

Acceso a internet


    Spearman's rank correlation rho

data:  data$p_alfabetizacion and data$p_internet
S = 749.51, p-value = 6.617e-05
alternative hypothesis: true rho is not equal to 0
sample estimates:
     rho 
0.711728 

Instituciones bilingues


    Spearman's rank correlation rho

data:  data$p_alfabetizacion and data$EIB
S = 4627.4, p-value = 4.325e-06
alternative hypothesis: true rho is not equal to 0
sample estimates:
       rho 
-0.7797711 

4. Regresiones

Column {data-width=500}

Regresión Gaussiana

Resumen de Regresion Lineal
 OLS asegurados (I)
(Intercept) 81.425
(83.541)
c_lenguas -0.065
(0.375)
p_lenguasnativas -0.108
(0.151)
p_mujer 1.135
(2.122)
p_rural -0.531
(0.397)
p_motora -0.216
(2.310)
p_intelectual -7.568
(12.745)
p_internet -0.543
(0.552)
EIB 0.000
(0.013)
Num.Obs. 25
R2 0.386
R2 Adj. 0.078
AIC 196.8
BIC 209.0
Log.Lik. -88.412
F 1.255
RMSE 8.31
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001

Analizando regresión gaussiana

Normalidad 1

Normalidad 2

Tests de normalidad

  testshapiro$p.value testKS$p.value testKS$statistic
1        8.442339e-07              0                1

Column {data-width=500}

Regresión Poisson

Regresión Poisson - coeficientes exponenciados
 POISSON dependientes (I)
(Intercept) 20476.0388***
[4001.2234, 104296.3999]
c_lenguas 0.9821***
[ 0.9745, 0.9898]
p_lenguasnativas 0.9874***
[ 0.9843, 0.9905]
p_mujer 0.8413***
[ 0.8057, 0.8782]
p_rural 1.0337***
[ 1.0249, 1.0427]
p_motora 1.0399
[ 0.9879, 1.0942]
p_intelectual 0.3891***
[ 0.2925, 0.5177]
p_internet 1.0995***
[ 1.0874, 1.1117]
EIB 0.9998+
[ 0.9995, 1.0000]
Num.Obs. 25
AIC 407.7
BIC 418.7
Log.Lik. -194.847
F 372.902
RMSE 27.92
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001

Test de Equidispersión

Test de Equidispersión
Es probable?
overdispersion TRUE
underdispersion FALSE

Comparando modelos

EXP() de la Regresiones Poisson, Quasi Poisson y Binomial Negativa
 Poisson asegurados (II)  QuasiPoisson asegurados (II)  Binomial Negativa asegurados (II)
(Intercept) 20476.0388*** 20476.0388** 84940.0700***
[4001.2234, 104296.3999] [37.8230, 10358854.6546] [424.3671, 18546946.4519]
c_lenguas 0.9821*** 0.9821 0.9854
[ 0.9745, 0.9898] [ 0.9527, 1.0112] [ 0.9632, 1.0085]
p_lenguasnativas 0.9874*** 0.9874* 0.9875**
[ 0.9843, 0.9905] [ 0.9755, 0.9995] [ 0.9784, 0.9966]
p_mujer 0.8413*** 0.8413* 0.8197**
[ 0.8057, 0.8782] [ 0.7116, 0.9906] [ 0.7185, 0.9360]
p_rural 1.0337*** 1.0337* 1.0344**
[ 1.0249, 1.0427] [ 1.0011, 1.0695] [ 1.0103, 1.0586]
p_motora 1.0399 1.0399 1.0218
[ 0.9879, 1.0942] [ 0.8522, 1.2607] [ 0.8934, 1.1725]
p_intelectual 0.3891*** 0.3891+ 0.4364*
[ 0.2925, 0.5177] [ 0.1306, 1.1648] [ 0.2077, 0.9173]
p_internet 1.0995*** 1.0995*** 1.0957***
[ 1.0874, 1.1117] [ 1.0542, 1.1475] [ 1.0586, 1.1343]
EIB 0.9998+ 0.9998 0.9996
[ 0.9995, 1.0000] [ 0.9987, 1.0007] [ 0.9989, 1.0004]
Num.Obs. 25 25 25
AIC 407.7 258.7
BIC 418.7 270.8
Log.Lik. -194.847 -119.326
F 372.902 25.441 39.967
RMSE 27.92 27.92 32.81
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001

Test ANOVA

Tabla ANOVA para comparar modelos
Resid. Df Resid. Dev Df Deviance Pr(>Chi)
16 231.60106 NA NA NA
16 231.60106 0 0.0000 NA
16 25.35593 0 206.2451 NA

Comparando coeficientes

Coeficientes Standarizados (ordenar vía valores absolutos)
Poisson CuasiPoisson BinomNegativa
EIB -0.6508871 -0.6508871 -0.5320867
c_lenguas -0.0071820 -0.0071820 -0.0071187
p_lenguasnativas -0.0385090 -0.0385090 -0.0314803
p_mujer -0.0019531 -0.0019531 -0.0019359
p_rural -0.0358312 -0.0358312 -0.0292913
p_motora -0.0038149 -0.0038149 -0.0037812
p_intelectual -0.0009684 -0.0009684 -0.0007916
p_internet -0.0130095 -0.0130095 -0.0128948

5. Clusters

Column {data-width=1000}

Datos

Visualización Correlación

Diana

silhouette

Mal clusterizado

[1] "JUNIN"
  diana      EIB c_lenguas p_lenguasnativas p_alfabetizacion  p_mujer  p_rural
1     1 775.3333  20.66667         61.19333         85.63333 49.62667 64.15000
2     2 782.2857  11.85714         68.87000         78.12857 51.82000 45.11571
3     3  66.0000  13.40000         33.35000         92.54667 50.22000 18.41133
   p_motora p_intelectual p_internet
1  7.597412      1.319940   4.488361
2 15.622452      2.597790   9.161885
3 14.268188      2.112846  23.468600
                      [,1]        [,2]
AMAZONAS      -0.346944822  0.25527425
ANCASH        -0.213820653 -0.11325638
APURIMAC      -0.274295034 -0.14765093
AREQUIPA       0.172716222 -0.19000194
AYACUCHO      -0.236907631 -0.12348508
CAJAMARCA      0.062941817  0.17025059
CALLAO         0.276075190 -0.21873443
CUSCO         -0.254696329 -0.22665733
HUANCAVELICA  -0.317195722 -0.03652616
HUANUCO       -0.162715583 -0.01523155
ICA            0.223507950 -0.12671776
JUNIN         -0.030345218 -0.05892686
LA LIBERTAD    0.314741683  0.15713916
LAMBAYEQUE     0.077350361  0.07577600
LIMA           0.282202606 -0.17372238
LORETO        -0.283713242  0.28505783
MADRE DE DIOS  0.136745896  0.09959105
MOQUEGUA       0.135760581 -0.16754537
PASCO         -0.008413013  0.04980372
PIURA          0.213988005  0.23250531

Graf. de distancias

Graf. de distancias DIANA

6. Conclusiones

---
title: "Análisis de la alfabetización de la comunidad indígena y originaria en el Perú"
author: Joicy Torrejon & Gianfranco Risso
output: 
  flexdashboard::flex_dashboard:
    social: menu
    source_code: embed
---


1. Introducción {data-icon="fa-signal"}
===================================== 

Column {data-width= 700}
-----------------------------------------------------------------------

```{r}
library(tmap) #Dibujar el mapa
library(sf) #Para leer el shapefile y reducir el tamaño del archivo
library(pryr) #Calcular el tamaño del archivo
library("readr") #para cargar csv
library(base) # para merge
library(reshape2) # para hacer dcast
library(plyr) # para mineria en csv 
library(dplyr) # para inner join
library(readxl)
```


```{r}
library(rio)
data=import("dataalfabetizacion.xlsx")
```



```{r, include=FALSE}
setwd("C:/Users/joicy/Downloads/trabajo")

shp_departamentos <- st_read("DEPARTAMENTOS_inei_geogpsperu_suyopomalia/DEPARTAMENTOS_inei_geogpsperu_suyopomalia.shp")

```


```{r}
shp_departamentos <- inner_join(shp_departamentos,data,by="NOMBDEP")
```

```{r}

tmap_mode("view")
```


```{r}
tm_shape(shp_departamentos) +
  tm_fill("p_alfabetizacion", id="NOMBDEP", palette = "Oranges", style="quantile", title="% alfabetización") +
  tm_borders("grey25", alpha=.05) + 
  tm_layout("Porcentaje de alfabetización de la población indígena y originaria por departamento en 2017",
            main.title.position = "center") + tm_view(view.legend.position = c("left","bottom") #esto sirve para bajar la leyenda y que no estorbe con el título 
            )

tmap_last <- tmap_last()

```


Column {data-width= 300}
-----------------------------------------------------------------------

### Hipótesis

A nivel departamental, el porcentaje de alfabetismo está afectado por el porcentaje de personas nativas que asisten actualmente a un centro educativo, la cantidad de lenguas nativas habladas, el porcentaje de personas que hablan lenguas nativas, el porcentaje de población femenina, el porcentaje de personas que viven en el área rural, el porcentaje de personas que sufren una discapacidad motora, el porcentaje de personas que sufren una discapacidad intelectual y el porcentaje de hogares que tienen acceso a internet.





2. Variable central {data-icon="fa-signal"}
===================================== 

Column {data-width=500} {.tabset}
-----------------------------------------------------------------------

### Histograma del porcentaje de alfabetización

```{r}

library(ggplot2)

baseHist= ggplot(data=data, aes(x=p_alfabetizacion))
histoAlfa=baseHist + geom_histogram(bins=8)
histoAlfa
```

### Boxplot

```{r}
library(ggplot2)
ggplot(data, aes(y = p_alfabetizacion)) +
  geom_boxplot()
```



Column {data-width=500} {.tabset}
-----------------------------------------------------------------------

### Tabla de frecuencias

```{r}

# Tabla de frecuencias

TF_Alfa=summary(data$p_alfabetizacion)
TF_Alfa

```



3. Correlación (VD vs VIs) {data-icon="fa-signal"}
===================================== 

Column {data-width=750} {.tabset}
-----------------------------------------------------------------------

### N°lenguas nativas

```{r}
library(ggplot2)

base=ggplot(data=data, aes(x=c_lenguas, y=p_alfabetizacion))
scatter2 = base + geom_point()
library(ggrepel)
scatterText2 = scatter2 + geom_text_repel(aes(label=NOMBDEP),size=2)
scatterText2

```

### % lenguas nativas

```{r}
library(ggplot2)

base=ggplot(data=data, aes(x=p_lenguasnativas, y=p_alfabetizacion))
scatter3 = base + geom_point()
library(ggrepel)
scatterText3 = scatter3 + geom_text_repel(aes(label=NOMBDEP),size=2)
scatterText3
```


### Población femenina 

```{r}
library(ggplot2)

base=ggplot(data=data, aes(x=p_mujer, y=p_alfabetizacion))
scatter4 = base + geom_point()
library(ggrepel)
scatterText4 = scatter4 + geom_text_repel(aes(label=NOMBDEP),size=2)
scatterText4
```

### Población rural

```{r}
library(ggplot2)

base=ggplot(data=data, aes(x=p_rural, y=p_alfabetizacion))
scatter5 = base + geom_point()
library(ggrepel)
scatterText5 = scatter5 + geom_text_repel(aes(label=NOMBDEP),size=2)
scatterText5
```

### Discapacidad motora

```{r}
library(ggplot2)

base=ggplot(data=data, aes(x=p_motora, y=p_alfabetizacion))
scatter6 = base + geom_point()
library(ggrepel)
scatterText6 = scatter6 + geom_text_repel(aes(label=NOMBDEP),size=2)
scatterText6
```

### Discapacidad intelectual

```{r}
library(ggplot2)

base=ggplot(data=data, aes(x=p_intelectual, y=p_alfabetizacion))
scatter7 = base + geom_point()
library(ggrepel)
scatterText7 = scatter7 + geom_text_repel(aes(label=NOMBDEP),size=2)
scatterText7
```


### Acceso a internet

```{r}
library(ggplot2)

base=ggplot(data=data, aes(x=p_internet, y=p_alfabetizacion))
scatter8 = base + geom_point()
library(ggrepel)
scatterText8 = scatter8 + geom_text_repel(aes(label=NOMBDEP),size=2)
scatterText8
```


### Instituciones bilingues

```{r}
library(ggplot2)

base=ggplot(data=data, aes(x=p_internet, y=EIB))
scatter8 = base + geom_point()
library(ggrepel)
scatterText8 = scatter8 + geom_text_repel(aes(label=NOMBDEP),size=2)
scatterText8
```


Column {data-width=250} {.tabset}
-----------------------------------------------------------------------


### N°lenguas nativas

```{r}
cor.test(data$p_alfabetizacion, data$c_lenguas, method = c("spearman"))
```


### % lenguas nativas

```{r}
cor.test(data$p_alfabetizacion, data$p_lenguasnativas, method = c("spearman"))
```


### Población femenina

```{r}
cor.test(data$p_alfabetizacion, data$p_mujer, method = c("spearman"))
```


### Población rural

```{r}
cor.test(data$p_alfabetizacion, data$p_rural, method = c("spearman"))
```


### Discapacidad motora

```{r}
cor.test(data$p_alfabetizacion, data$p_motora, method = c("spearman"))
```


### Discapacidad intelectual

```{r}
cor.test(data$p_alfabetizacion, data$p_intelectual, method = c("spearman"))
```


### Acceso a internet

```{r}
cor.test(data$p_alfabetizacion, data$p_internet, method = c("spearman"))
```

### Instituciones bilingues

```{r}
cor.test(data$p_alfabetizacion, data$EIB, method = c("spearman"))
```

4. Regresiones {data-icon="fa-signal"}
===================================== 

Column {data-width=500} {.tabset}
-----------------------------------------------------------------------

### Regresión Gaussiana

```{r}
modelo1=formula(p_alfabetizacion~c_lenguas+p_lenguasnativas+p_mujer+p_rural+p_motora+p_intelectual+p_internet+EIB)
```


```{r}
reg1=lm(modelo1,data=data)

library(knitr)
library(modelsummary)

model1=list('OLS asegurados (I)'=reg1)
modelsummary(model1, title = "Resumen de Regresion Lineal",
             stars = TRUE,
             output = "kableExtra")
```

### Analizando regresión gaussiana

```{r}
par(mfrow = c(2, 2))  
plot(reg1, 1,caption = '');title(main="Linealidad")
plot(reg1, 2, caption = '');title(main="Normalidad")
plot(reg1, 3, caption = '');title(main="Homocedasticidad")
plot(reg1, 5, caption = '');title(main="Influyentes")
```

### Normalidad 1

```{r}
library(ggh4x)

baseHist +
  geom_histogram(aes(y =after_stat(density)),bins=8) +
  stat_theodensity(colour = "red") 
```

### Normalidad 2

```{r}
library(ggpubr)
ggqqplot(data$p_alfabetizacion)
```


### Tests de normalidad


```{r}
library(dplyr)
library(tidyr)

testshapiro <- shapiro.test(data$p_alfabetizacion)

testKS <- ks.test(data$p_alfabetizacion,'pnorm')

resultados <- data %>%
  summarise(testshapiro$p.value,
            testKS$p.value,
            testKS$statistic)
resultados
```



Column {data-width=500} {.tabset}
-----------------------------------------------------------------------

### Regresión Poisson

```{r}
library(knitr)
library(modelsummary)
rp1=glm(modelo1, data = data, 
        offset=log(p_pueblosnativos), #exposure 
        family = poisson(link = "log"))
modelsPois = list('POISSON dependientes (I)' = rp1)

# formula para limitar a 4 digitos decimales, 
# sin que se muestre notación científica:
formatoNum <- function(x) format(x, digits = 4, scientific = FALSE)

modelsummary(modelsPois,
             fmt=formatoNum, # uso mi formula
             exponentiate = T, # exponenciar!!!!!
             statistic = 'conf.int',
             title = "Regresión Poisson - coeficientes exponenciados",
             stars = TRUE,
             output = "kableExtra")

```


### Test de Equidispersión

```{r}
library(magrittr)
library(AER)
overdispersion=AER::dispersiontest(rp1,alternative='greater')$ p.value<0.05
underdispersion=AER::dispersiontest(rp1,alternative='less')$ p.value<0.05
# tabla
testResult=as.data.frame(rbind(overdispersion,underdispersion))
names(testResult)='Es probable?'
testResult%>%kable(caption = "Test de Equidispersión")%>%kableExtra::kable_styling()
```


### Comparando modelos 

```{r}
rqp = glm(modelo1, data = data,
          offset=log(p_pueblosnativos),
          family = quasipoisson(link = "log"))

modelsQPexp=list('QuasiPoisson asegurados (II) exponenciado'=rqp)

library(MASS)

h2off=formula(p_alfabetizacion ~c_lenguas+p_lenguasnativas+p_mujer+p_rural+p_motora+p_intelectual+p_internet + EIB + offset(log(p_pueblosnativos)))

rbn=glm.nb(h2off,data=data)

modelsQP_BN=list('Poisson asegurados (II)'=rp1,
                 'QuasiPoisson asegurados (II)'=rqp,
                 'Binomial Negativa asegurados (II)'=rbn)


modelsummary(modelsQP_BN,fmt=formatoNum,
             exponentiate = T, 
             statistic = 'conf.int',
             title = "EXP() de la Regresiones Poisson, Quasi Poisson  y Binomial Negativa",
             stars = TRUE,
             output = "kableExtra")
```




### Test ANOVA

```{r}
anova(rp1,rqp,rbn, test = "Chisq") %>%
kable(caption = "Tabla ANOVA para comparar modelos")%>%kableExtra::kable_styling(full_width = FALSE)
```




### Comparando coeficientes

```{r}
sdVD=sd(data$p_alfabetizacion)
sdVIs=apply(data[,c("EIB", "c_lenguas","p_lenguasnativas","p_mujer","p_rural","p_motora","p_intelectual","p_internet")],2,sd)
DF=list(Poisson=sdVIs*coef(rp1)[c(2,3)]/sdVD,
     CuasiPoisson=sdVIs*coef(rqp)[c(2,3)]/sdVD,
     BinomNegativa=sdVIs*coef(rbn)[c(2,3)]/sdVD)%>%
       data.frame()

DF%>% kable(caption = "Coeficientes Standarizados (ordenar vía valores absolutos)")%>%
          kableExtra::kable_styling(full_width = F)
```



5. Clusters {data-icon="fa-signal"}
===================================== 

Column {data-width=1000} {.tabset}
-----------------------------------------------------------------------

### Datos

```{r}
library(BBmisc)

boxplot(normalize(data[,c(2:11)],method='range',range=c(0,10)))
```

### Visualización Correlación 

```{r}
dontselect=c("NOMBDEP","p_pueblosnativos")
select=setdiff(names(data),dontselect) 
theData=data[,select]
```


```{r}
library(polycor)
corMatrix=polycor::hetcor(theData)$correlations
```



```{r}
library(ggcorrplot)

ggcorrplot(corMatrix)
```


```{r}
row.names(theData)=data$NOMBDEP
```

```{r}
library(cluster)
g.dist = daisy(theData, metric="gower")
```

### Diana


```{r}
library(factoextra)
set.seed(123)
res.diana <- hcut(g.dist, k = 3,hc_func='diana')
theData$diana=res.diana$cluster

```


```{r}
# Visualize
fviz_dend(res.diana, cex = 0.7, horiz = T, main = "")
```

### silhouette

```{r}
fviz_silhouette(res.diana,print.summary = F)
```


### Mal clusterizado


```{r}
silDIANA=data.frame(res.diana$silinfo$widths)
silDIANA$Departamentos=row.names(silDIANA)
poorDIANA=silDIANA[silDIANA$sil_width<0,'Departamentos']%>%sort()
poorDIANA
```

```{r}
aggregate(.~ diana, data=theData,mean)
```



```{r}
theData$diana=dplyr::recode(theData$diana, `2` = 1, `1`=2,`3`=3)
```


```{r}
data$dianapoor=data$NOMBDEP%in%poorDIANA
data$diana=as.ordered(theData$diana)
theData$diana=NULL
```


```{r}
# k es la cantidad de dimensiones
proyeccion = cmdscale(g.dist, k=2,add = T) 
head(proyeccion$points,20)
```



```{r}
# data frame prep:
data$dim1 <- proyeccion$points[,1]
data$dim2 <- proyeccion$points[,2]
```

### Graf. de distancias 


```{r}
library(ggrepel)
base= ggplot(data,aes(x=dim1, y=dim2,label=row.names(theData))) 
base + geom_text_repel(size=3, max.overlaps = 50,min.segment.length = unit(0, 'lines'))
```

### Graf. de distancias DIANA

```{r}
library(ggplot2)
# solo paises mal clusterizados
DIANAlabels=ifelse(data$dianapoor,data$NOMBDEP,'')

dianaPlot=base + geom_point(size=3,
                            aes(color=diana)) 

dianaPlot + geom_text_repel(size=3, max.overlaps = 50,min.segment.length = unit(0, 'lines'))


```


6. Conclusiones {data-icon="fa-signal"}
=====================================