Estadistica para el analisis politico 2 - POL304


CONFLICTOS SOCIALES: UN ESTUDIO SOBRE LAS CAUSAS DE ESTE FENOMENO EN EL GOBIERNO DE OLLANTA HUMALA 20011-2016


  1. Índice

1.Carga de datos

El siguiente trabajo tiene como objetivo identificar las causas de el inicio de los conflcitos sociales, para esto a tomado como variables la presencia del estado medido en IDE, desarrollo humano medido en IDH y el voto a Ollanta Humala en el año 2011. Como variables de control estamos usando el canon por provincia modificado y la poblacion,

2.Limpieza de la base de datos

Cargamos la data de Conflictos sociales

link="https://docs.google.com/spreadsheets/d/e/2PACX-1vSDNLWQrRs09K-Si_W9Zqam5-7cFEF0C47o_baVll3x9Peup76gR05KJyA81c0Szc6oe_cHv_RWlFJr/pub?output=xlsx"

library(openxlsx)

CONFLICTOS=read.xlsx(link, 
                sheet = 1, #hoja que cargaremos, corresponde al año 2011. 
                startRow = 0, #desde esta fila empezaremos a leer, aseguremonos de no perder títulos
                skipEmptyRows = T, skipEmptyCols = T)

head(CONFLICTOS)
##   TXUBIGEO DEPARTAMENTO    Provincia     Distrito           TIPO AÑO_CAT
## 1   010108     AMAZONAS  CHACHAPOYAS      HUANCAS        LOCALES       0
## 2   010206     AMAZONAS        BAGUA        IMAZA        LOCALES       0
## 3   010311     AMAZONAS      BONGARA YAMBRASBAMBA SOCIOAMBIENTAL       0
## 4   010417     AMAZONAS         LUYA SAN JERONIMO        LOCALES       0
## 5   010601     AMAZONAS CONDORCANQUI        NIEVA SOCIOAMBIENTAL       0
## 6   010602     AMAZONAS CONDORCANQUI RIO SANTIAGO        LOCALES       1
##   ANIO_inicio Mes_inicio
## 1        2002       <NA>
## 2        2006        Jun
## 3        2008        Ago
## 4        2007        Feb
## 5        2010        Feb
## 6        2011        Jul

Elimnamos los conflictos que no se encuentren en el periodo de nuestro estudio

CONFLICTOS=CONFLICTOS[!CONFLICTOS$ANIO_inicio=="2017",]

Eliminamos columnas innecesaarias

CONFLICTOS=CONFLICTOS[-c(2,3,7,8)]

Revisamos el nombre de las columnas

names(CONFLICTOS)
## [1] "TXUBIGEO" "Distrito" "TIPO"     "AÑO_CAT"

Cambiamos el nombre de las columnas

names(CONFLICTOS)=c("ubigeoDistrito","DISTRITO","TIPOCONFLICTO","CATEGORIA")

Creamos un subset con la informacion de los conflictos del periodo 2002-2011(hasta Junio)

ANTESOLLANTA=CONFLICTOS[CONFLICTOS$CATEGORIA=="0",]

Eliminamos la columna categoria porque ya no la necesitaremos

ANTESOLLANTA=ANTESOLLANTA[-c(4)]

Agrupamos los tipos de conflicto por distrito y lo transformamos a numero de conflictos por distrito

library(tidyverse)
## -- Attaching packages ---------------------------------------------------------------------------------- tidyverse 1.2.1 --
## v ggplot2 3.1.0     v purrr   0.2.5
## v tibble  1.4.2     v dplyr   0.7.7
## v tidyr   0.8.2     v stringr 1.3.1
## v readr   1.1.1     v forcats 0.3.0
## -- Conflicts ------------------------------------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
ANTES_OLLANTA= ANTESOLLANTA %>% group_by(DISTRITO) %>% summarise(TIPOCONFLICTO=n())
ANTESOLLANTA=ANTESOLLANTA[-c(3)]
ANTESOLLANTA=merge(ANTESOLLANTA,ANTES_OLLANTA,by="DISTRITO")
ANTESOLLANTA<- ANTESOLLANTA[!duplicated(ANTESOLLANTA$ubigeoDistrito), ]
ANTESOLLANTA<- ANTESOLLANTA[!duplicated(ANTESOLLANTA$DISTRITO), ]
ANTESOLLANTA$TIPOCONFLICTO=factor(ANTESOLLANTA$TIPOCONFLICTO,
                   levels = c(1:8),
                   ordered = T)

str(ANTESOLLANTA)
## 'data.frame':    396 obs. of  3 variables:
##  $ DISTRITO      : chr  "ACARI" "ACCHA" "ACO" "ACOCHACA" ...
##  $ ubigeoDistrito: chr  "040402" "071002" "110202" "021802" ...
##  $ TIPOCONFLICTO : Ord.factor w/ 8 levels "1"<"2"<"3"<"4"<..: 1 3 1 1 1 2 4 1 1 2 ...
ANTESOLLANTA=ANTESOLLANTA[-c(1)]

Cambiamos el nombre de la columna

names(ANTESOLLANTA)=c("ubigeoRENIEC","NUMEROCONFLICTOS")
head(ANTESOLLANTA)
##   ubigeoRENIEC NUMEROCONFLICTOS
## 1       040402                1
## 2       071002                3
## 5       110202                1
## 6       021802                1
## 7       070202                1
## 8       200102                2

Creamos un subset con la informacion de los conflictos del periodo 20011(desde Julio)-2016

DURANTEOLLANTA=CONFLICTOS[CONFLICTOS$CATEGORIA=="1",]

Eliminamos la columna categoria porque ya no la necesitaremos

DURANTEOLLANTA=DURANTEOLLANTA[-c(4)]

Agrupamos los tipos de conflicto por distrito y lo transformamos a numero de conflictos por distrito

library(tidyverse)
DURANTE_OLLANTA= DURANTEOLLANTA %>% group_by(DISTRITO) %>% summarise(TIPOCONFLICTO=n())

Eliminamos columnas innecesaria

DURANTEOLLANTA=DURANTEOLLANTA[-c(3)]

Hacemosun merge para poder juntar el ubigeo

DURANTEOLLANTA=merge(DURANTEOLLANTA,DURANTE_OLLANTA,by="DISTRITO")

Borramos los distritos duplicados

DURANTEOLLANTA<- DURANTEOLLANTA[!duplicated(DURANTEOLLANTA$DISTRITO), ]

Borramos los ubigeos duplicados

DURANTEOLLANTA<- DURANTEOLLANTA[!duplicated(DURANTEOLLANTA$ubigeoDistrito), ]

convertimos a factor nuestra variable

DURANTEOLLANTA$TIPOCONFLICTO=factor(DURANTEOLLANTA$TIPOCONFLICTO,
                   levels = c(1:8),
                   ordered = T)

str(DURANTEOLLANTA)
## 'data.frame':    230 obs. of  3 variables:
##  $ DISTRITO      : chr  "ABANCAY" "ACARI" "ACOBAMBA" "AGALLPAMPA" ...
##  $ ubigeoDistrito: chr  "030101" "040402" "021407" "120402" ...
##  $ TIPOCONFLICTO : Ord.factor w/ 8 levels "1"<"2"<"3"<"4"<..: 2 1 1 1 2 1 1 2 1 1 ...

Eliminamos columna innecesaria

DURANTEOLLANTA=DURANTEOLLANTA[-c(1)]

Cambiamos el nombre de la columna

names(DURANTEOLLANTA)=c("ubigeoRENIEC","NUMEROCONFLICTOS")
head(DURANTEOLLANTA)
##   ubigeoRENIEC NUMEROCONFLICTOS
## 1       030101                2
## 3       040402                1
## 4       021407                1
## 5       120402                1
## 6       020201                2
## 8       200302                1

Entonces nos quedamos con dos subdata, una con el numero de conflictos sociales antes del periodo de Ollanta y otra con el periodo durante el gobierno de Ollanta

Variable Voto a Ollanta

Cargamos la data del voto a Ollanta

link="https://docs.google.com/spreadsheets/d/e/2PACX-1vSfefCO_LgxyDcrW53lKcCQ5GYOVwkGVaZLRKNEyD75RvnOG0snGLpTdz5oH0HZi_IjOG5QI0uRZMCx/pub?output=xlsx"

library(openxlsx)

VOTO=read.xlsx(link, 
                sheet = 1, #hoja que cargaremos, corresponde al año 2011. 
                startRow = 0, #desde esta fila empezaremos a leer, aseguremonos de no perder títulos
                skipEmptyRows = T, skipEmptyCols = T)

head(VOTO)
##   DEPARTAMENTO   PROVINCIA    DISTRITO UBIGEO PPK2011PORPV KEIKO2011PORPV
## 1     AMAZONAS CHACHAPOYAS CHACHAPOYAS 010101  0.132669537      0.2378005
## 2     AMAZONAS CHACHAPOYAS    ASUNCION 010102  0.035714286      0.2500000
## 3     AMAZONAS CHACHAPOYAS      BALSAS 010103  0.029795158      0.5623836
## 4     AMAZONAS CHACHAPOYAS       CHETO 010104  0.022284123      0.3036212
## 5     AMAZONAS CHACHAPOYAS   CHILIQUIN 010105  0.006430868      0.6012862
## 6     AMAZONAS CHACHAPOYAS CHUQUIBAMBA 010106  0.028391167      0.4463722
##   OLLANTA2011PORPV KEIKO2011PORSV1 OLLANTA2011PORSV1
## 1        0.2665052       0.4247242         0.5752758
## 2        0.2928571       0.2866242         0.7133758
## 3        0.1378026       0.6582278         0.3417722
## 4        0.4623955       0.3615385         0.6384615
## 5        0.2636656       0.6262376         0.3737624
## 6        0.2113565       0.5957447         0.4042553

Nos quedamos con las columnas que contengan el voto de primera a Ollanta

VOTO=VOTO[,c(3,4,7)]

Cambiamos los nombres de las columnas

names(VOTO)=c("DISTRITO","ubigeoRENIEC","OLLANTA1V")

Variable IDH

Cargamos la data de IDH a nivel distital

link="https://docs.google.com/spreadsheets/d/e/2PACX-1vRpichn0BLDJqJGEiLyveLHRoW--m52gn7PFxMgwM93gl2vN4lSz0Q5RetqtzmlwpOIwKfnqBW2p6kY/pub?output=xlsx"

library(openxlsx)

IDHPERU=read.xlsx(link, 
                sheet = 1, #hoja que cargaremos, corresponde al año 2011. 
                startRow = 5, #desde esta fila empezaremos a leer, aseguremonos de no perder títulos
                skipEmptyRows = T, skipEmptyCols = T)

head(IDHPERU)
##       X1       X2     Distrito habitantes ranking       IDH ranking
## 1 000000 PERÚ  a/         <NA>   30135875      NA 0.5058382      NA
## 2 010000 AMAZONAS         <NA>     417508      19 0.3845648      19
## 3 010100     <NA>  Chachapoyas      54783     114 0.4343753      60
## 4 010101      1.0 Chachapoyas       27737     192 0.5467212     136
## 5 010102      2.0 Asuncion            296    1825 0.1683225    1747
## 6 010103      3.0    Balsas          1590    1462 0.2633761    1214
##       años ranking          % ranking     años ranking N.S..mes ranking
## 1 74.31045      NA 67.8731952      NA 8.995900      NA 696.9370      NA
## 2 73.98588      10 53.6528783      19 6.661000      20 435.6736      18
## 3 73.95475      80 45.4878254     100 7.799699      64 599.8076      45
## 4 73.38709     918 62.7192982     476 9.968829     159 866.5725     103
## 5 73.28082     931  0.7514946    1823 6.079101    1068 341.9903     846
## 6 71.96708    1128 14.4828735    1707 5.282190    1362 340.2772     854

Verificamos si en la cola hay valores que debemos borrar

tail(IDHPERU)
##                                                                                                                                                                                                                      X1
## 2057 a/ Incluye las cifras estimadas del distrito de Carmen Alto en la provincia de Huamanga, departamento de Ayacucho, donde. Autoridades locales no permitieron la ejecución del Censo de Población y Vivienda 2007. 
## 2058                                                                                                       1/ Cifras estimadas. Autoridades locales no permitieron la ejecución del Censo de Población y Vivienda 2007.
## 2059                                                                                                 2/ Incluye a la población ubicada en área temporal por límites de fronteras de los distritos de Pangoa y Mazamari.
## 2060                                                                                                                                                                                    3/ Provincias de Lima y Callao.
## 2061                                                                                                                                                 Fuente: INEI. Censo de Población y Vivienda 2007. ENAHO y ENAPRES.
## 2062                                                                                                                                                                                            Elaboración: PNUD-Perú.
##        X2 Distrito habitantes ranking IDH ranking años ranking  % ranking
## 2057 <NA>     <NA>         NA      NA  NA      NA   NA      NA NA      NA
## 2058 <NA>     <NA>         NA      NA  NA      NA   NA      NA NA      NA
## 2059 <NA>     <NA>         NA      NA  NA      NA   NA      NA NA      NA
## 2060 <NA>     <NA>         NA      NA  NA      NA   NA      NA NA      NA
## 2061 <NA>     <NA>         NA      NA  NA      NA   NA      NA NA      NA
## 2062 <NA>     <NA>         NA      NA  NA      NA   NA      NA NA      NA
##      años ranking N.S..mes ranking
## 2057   NA      NA       NA      NA
## 2058   NA      NA       NA      NA
## 2059   NA      NA       NA      NA
## 2060   NA      NA       NA      NA
## 2061   NA      NA       NA      NA
## 2062   NA      NA       NA      NA

Eliminamos filas innecesarias

IDHPERU = IDHPERU[-c(2057:2062),] 
tail(IDHPERU)
##          X1   X2      Distrito habitantes ranking       IDH ranking
## 2051 250300 <NA>    Padre Abad      56756     111 0.3728368      82
## 2052 250301  1.0 Padre Abad         26364     212 0.4161015     476
## 2053 250302  2.0    Irazola         22779     243 0.3283280     808
## 2054 250303  3.0    Curimana         7613     641 0.3039023     962
## 2055 250400 <NA>         Purús       4251     195 0.2862257     138
## 2056 250401  1.0        Purus        4251     957 0.2862257    1076
##          años ranking        % ranking     años ranking N.S..mes ranking
## 2051 78.77254      17 38.73143     121 7.193236      87 406.6648      88
## 2052 77.62689     326 44.32234     914 7.676127     572 507.7652     463
## 2053 78.89258     200 31.03530    1268 6.657738     861 333.1001     878
## 2054 78.83507     213 28.93897    1322 6.795543     823 276.6664    1053
## 2055 68.60871     157 17.43073     191 7.233476      86 342.9416     105
## 2056 68.60871    1473 17.43073    1635 7.233476     685 342.9416     843

Revisamos si es que en la parte superior tambien hay filas innecesarias

head(IDHPERU)
##       X1       X2     Distrito habitantes ranking       IDH ranking
## 1 000000 PERÚ  a/         <NA>   30135875      NA 0.5058382      NA
## 2 010000 AMAZONAS         <NA>     417508      19 0.3845648      19
## 3 010100     <NA>  Chachapoyas      54783     114 0.4343753      60
## 4 010101      1.0 Chachapoyas       27737     192 0.5467212     136
## 5 010102      2.0 Asuncion            296    1825 0.1683225    1747
## 6 010103      3.0    Balsas          1590    1462 0.2633761    1214
##       años ranking          % ranking     años ranking N.S..mes ranking
## 1 74.31045      NA 67.8731952      NA 8.995900      NA 696.9370      NA
## 2 73.98588      10 53.6528783      19 6.661000      20 435.6736      18
## 3 73.95475      80 45.4878254     100 7.799699      64 599.8076      45
## 4 73.38709     918 62.7192982     476 9.968829     159 866.5725     103
## 5 73.28082     931  0.7514946    1823 6.079101    1068 341.9903     846
## 6 71.96708    1128 14.4828735    1707 5.282190    1362 340.2772     854

Eliminamos la fila Peru que es innecesario

IDHPERU=IDHPERU[-c(1),]
head(IDHPERU)
##       X1       X2     Distrito habitantes ranking       IDH ranking
## 2 010000 AMAZONAS         <NA>     417508      19 0.3845648      19
## 3 010100     <NA>  Chachapoyas      54783     114 0.4343753      60
## 4 010101      1.0 Chachapoyas       27737     192 0.5467212     136
## 5 010102      2.0 Asuncion            296    1825 0.1683225    1747
## 6 010103      3.0    Balsas          1590    1462 0.2633761    1214
## 7 010104      4.0      Cheto          608    1762 0.3274366     813
##       años ranking          % ranking     años ranking N.S..mes ranking
## 2 73.98588      10 53.6528783      19 6.661000      20 435.6736      18
## 3 73.95475      80 45.4878254     100 7.799699      64 599.8076      45
## 4 73.38709     918 62.7192982     476 9.968829     159 866.5725     103
## 5 73.28082     931  0.7514946    1823 6.079101    1068 341.9903     846
## 6 71.96708    1128 14.4828735    1707 5.282190    1362 340.2772     854
## 7 77.83988     308 44.6136813     899 4.961860    1480 346.7647     829

Eliminamos columnas innecesarias

columnas=c(seq(5,15,2))
IDHPERU <- IDHPERU[,-columnas]
head(IDHPERU)
##       X1       X2     Distrito habitantes       IDH     años          %
## 2 010000 AMAZONAS         <NA>     417508 0.3845648 73.98588 53.6528783
## 3 010100     <NA>  Chachapoyas      54783 0.4343753 73.95475 45.4878254
## 4 010101      1.0 Chachapoyas       27737 0.5467212 73.38709 62.7192982
## 5 010102      2.0 Asuncion            296 0.1683225 73.28082  0.7514946
## 6 010103      3.0    Balsas          1590 0.2633761 71.96708 14.4828735
## 7 010104      4.0      Cheto          608 0.3274366 77.83988 44.6136813
##     años.1 N.S..mes
## 2 6.661000 435.6736
## 3 7.799699 599.8076
## 4 9.968829 866.5725
## 5 6.079101 341.9903
## 6 5.282190 340.2772
## 7 4.961860 346.7647

Creamos una subdata con la informacion de regiones

REGIONES=IDHPERU[is.na(IDHPERU$Distrito),] 
head(IDHPERU)
##       X1       X2     Distrito habitantes       IDH     años          %
## 2 010000 AMAZONAS         <NA>     417508 0.3845648 73.98588 53.6528783
## 3 010100     <NA>  Chachapoyas      54783 0.4343753 73.95475 45.4878254
## 4 010101      1.0 Chachapoyas       27737 0.5467212 73.38709 62.7192982
## 5 010102      2.0 Asuncion            296 0.1683225 73.28082  0.7514946
## 6 010103      3.0    Balsas          1590 0.2633761 71.96708 14.4828735
## 7 010104      4.0      Cheto          608 0.3274366 77.83988 44.6136813
##     años.1 N.S..mes
## 2 6.661000 435.6736
## 3 7.799699 599.8076
## 4 9.968829 866.5725
## 5 6.079101 341.9903
## 6 5.282190 340.2772
## 7 4.961860 346.7647

Reseteamos el indice

row.names(REGIONES)=NULL
head(REGIONES)
##       X1        X2 Distrito habitantes       IDH     años        %  años.1
## 1 010000  AMAZONAS     <NA>     417508 0.3845648 73.98588 53.65288  6.6610
## 2 020000    ANCASH     <NA>    1129391 0.4429023 74.11191 57.00540  7.8884
## 3 030000  APURÍMAC     <NA>     451881 0.3444168 72.41378 60.57275  6.1528
## 4 040000  AREQUIPA     <NA>    1245251 0.5780632 75.97063 88.27166 10.0355
## 5 050000  AYACUCHO     <NA>     666029 0.3335711 70.21565 43.59124  6.3811
## 6 060000 CAJAMARCA     <NA>    1513892 0.3773468 73.83245 54.77661  6.4005
##   N.S..mes
## 1 435.6736
## 2 564.2242
## 3 330.7589
## 4 818.3624
## 5 358.7460
## 6 421.3008

Eliminamos las filas “Lima metropolitana” y “Region Lima provincias”

REGIONES=REGIONES[-c(15,16),]

Dejamos solo su nombre y Ubigeo, eliminamos las demas columnas

REGIONES=REGIONES[c(1,2)]

Colocamos nombre a nuestras columnas

colnames(REGIONES) = c("ubigeoRegion", "nombreRegion")

Creamos una subdata con la informacion de provincias

PROVINCIAS=IDHPERU[is.na(IDHPERU$X2),] 
head(PROVINCIAS)
##        X1   X2             Distrito habitantes       IDH     años
## 3  010100 <NA>          Chachapoyas      54783 0.4343753 73.95475
## 25 010200 <NA>                Bagua      77438 0.3866636 76.87897
## 32 010300 <NA>              Bongará      32317 0.3497911 73.36928
## 45 010400 <NA>         Condorcanqui      51802 0.1866263 70.39137
## 49 010500 <NA>                 Luya      52185 0.3075981 74.06573
## 73 010600 <NA> Rodríguez de Mendoza      30236 0.3310619 73.35318
##            %   años.1 N.S..mes
## 3  45.487825 7.799699 599.8076
## 25 39.843663 6.971553 467.6442
## 32 29.456796 6.464213 455.7142
## 45  8.012634 5.577313 180.0702
## 49 34.403834 5.504034 327.8493
## 73 26.603732 6.076635 427.0962

Reseteamos el indice

row.names(PROVINCIAS)=NULL
head(PROVINCIAS)
##       X1   X2             Distrito habitantes       IDH     años         %
## 1 010100 <NA>          Chachapoyas      54783 0.4343753 73.95475 45.487825
## 2 010200 <NA>                Bagua      77438 0.3866636 76.87897 39.843663
## 3 010300 <NA>              Bongará      32317 0.3497911 73.36928 29.456796
## 4 010400 <NA>         Condorcanqui      51802 0.1866263 70.39137  8.012634
## 5 010500 <NA>                 Luya      52185 0.3075981 74.06573 34.403834
## 6 010600 <NA> Rodríguez de Mendoza      30236 0.3310619 73.35318 26.603732
##     años.1 N.S..mes
## 1 7.799699 599.8076
## 2 6.971553 467.6442
## 3 6.464213 455.7142
## 4 5.577313 180.0702
## 5 5.504034 327.8493
## 6 6.076635 427.0962

Eliminamos la fila “Region lima provincias”

PROVINCIAS=PROVINCIAS[-c(129),]

Solo nos debemos quedar con el nombre de su provincia y el ubigeo

PROVINCIAS=PROVINCIAS[c(1,3)]

Le colocamos nombre a las columnas

colnames(PROVINCIAS) = c("ubigeoProvincia", "nombreProvincia")

Ahora creamos una subdata con la informacion de distritos

DISTRITOS=IDHPERU[complete.cases(IDHPERU),]
head(DISTRITOS)
##       X1  X2      Distrito habitantes       IDH     años          %
## 4 010101 1.0  Chachapoyas       27737 0.5467212 73.38709 62.7192982
## 5 010102 2.0  Asuncion            296 0.1683225 73.28082  0.7514946
## 6 010103 3.0     Balsas          1590 0.2633761 71.96708 14.4828735
## 7 010104 4.0       Cheto          608 0.3274366 77.83988 44.6136813
## 8 010105 5.0    Chiliquin         790 0.2115017 76.24811  8.0251613
## 9 010106 6.0 Chuquibamba         2146 0.2319344 70.87924 10.3547126
##     años.1 N.S..mes
## 4 9.968829 866.5725
## 5 6.079101 341.9903
## 6 5.282190 340.2772
## 7 4.961860 346.7647
## 8 4.439228 258.5687
## 9 6.152721 260.7576

La segunda columna no es necesaria asi que la eliminamos

DISTRITOS=DISTRITOS[,-c(2)] 

Colocamos nombre a las columnas

names(DISTRITOS) <- c("ubigeoDistrito", "DISTRITO", "habitantes", "IDH", "esperanza", "secundaria", "educacion", "ingresos")
head(DISTRITOS)
##   ubigeoDistrito      DISTRITO habitantes       IDH esperanza secundaria
## 4         010101  Chachapoyas       27737 0.5467212  73.38709 62.7192982
## 5         010102  Asuncion            296 0.1683225  73.28082  0.7514946
## 6         010103     Balsas          1590 0.2633761  71.96708 14.4828735
## 7         010104       Cheto          608 0.3274366  77.83988 44.6136813
## 8         010105    Chiliquin         790 0.2115017  76.24811  8.0251613
## 9         010106 Chuquibamba         2146 0.2319344  70.87924 10.3547126
##   educacion ingresos
## 4  9.968829 866.5725
## 5  6.079101 341.9903
## 6  5.282190 340.2772
## 7  4.961860 346.7647
## 8  4.439228 258.5687
## 9  6.152721 260.7576

Cambiamos los ubigeos para poder unir nuestras subdatas

#Ubigeo provincia: 
DISTRITOS$ubigeoProvincia=DISTRITOS$ubigeoDistrito
substr(DISTRITOS$ubigeoProvincia,5,6)='00'

#Ubigeo región: 
DISTRITOS$ubigeoRegion=DISTRITOS$ubigeoDistrito
substr(DISTRITOS$ubigeoRegion,3,6)='0000'

Reseteamos el indice de distrito

row.names(DISTRITOS)=NULL
head(DISTRITOS)
##   ubigeoDistrito      DISTRITO habitantes       IDH esperanza secundaria
## 1         010101  Chachapoyas       27737 0.5467212  73.38709 62.7192982
## 2         010102  Asuncion            296 0.1683225  73.28082  0.7514946
## 3         010103     Balsas          1590 0.2633761  71.96708 14.4828735
## 4         010104       Cheto          608 0.3274366  77.83988 44.6136813
## 5         010105    Chiliquin         790 0.2115017  76.24811  8.0251613
## 6         010106 Chuquibamba         2146 0.2319344  70.87924 10.3547126
##   educacion ingresos ubigeoProvincia ubigeoRegion
## 1  9.968829 866.5725          010100       010000
## 2  6.079101 341.9903          010100       010000
## 3  5.282190 340.2772          010100       010000
## 4  4.961860 346.7647          010100       010000
## 5  4.439228 258.5687          010100       010000
## 6  6.152721 260.7576          010100       010000

Juntamos las subdatas de provincia y region en la de distrito

IDHDISTRITOS = merge(DISTRITOS,PROVINCIAS, by="ubigeoProvincia", all.x=T)
IDHDISTRITOS = merge(IDHDISTRITOS, REGIONES, by="ubigeoRegion", all.x=T)

head(IDHDISTRITOS)
##   ubigeoRegion ubigeoProvincia ubigeoDistrito     DISTRITO habitantes
## 1       010000          010100         010101 Chachapoyas       27737
## 2       010000          010100         010104      Cheto          608
## 3       010000          010100         010105   Chiliquin         790
## 4       010000          010100         010102 Asuncion            296
## 5       010000          010100         010103    Balsas          1590
## 6       010000          010100         010112  Magdalena          856
##         IDH esperanza secundaria educacion ingresos nombreProvincia
## 1 0.5467212  73.38709 62.7192982  9.968829 866.5725     Chachapoyas
## 2 0.3274366  77.83988 44.6136813  4.961860 346.7647     Chachapoyas
## 3 0.2115017  76.24811  8.0251613  4.439228 258.5687     Chachapoyas
## 4 0.1683225  73.28082  0.7514946  6.079101 341.9903     Chachapoyas
## 5 0.2633761  71.96708 14.4828735  5.282190 340.2772     Chachapoyas
## 6 0.4012976  73.43866 36.7393695  6.271067 615.1609     Chachapoyas
##   nombreRegion
## 1     AMAZONAS
## 2     AMAZONAS
## 3     AMAZONAS
## 4     AMAZONAS
## 5     AMAZONAS
## 6     AMAZONAS

Ordenamos las columnas

IDHDISTRITOS<- IDHDISTRITOS[,c(1:3,12,11,4:10)]
head(IDHDISTRITOS)
##   ubigeoRegion ubigeoProvincia ubigeoDistrito nombreRegion nombreProvincia
## 1       010000          010100         010101     AMAZONAS     Chachapoyas
## 2       010000          010100         010104     AMAZONAS     Chachapoyas
## 3       010000          010100         010105     AMAZONAS     Chachapoyas
## 4       010000          010100         010102     AMAZONAS     Chachapoyas
## 5       010000          010100         010103     AMAZONAS     Chachapoyas
## 6       010000          010100         010112     AMAZONAS     Chachapoyas
##       DISTRITO habitantes       IDH esperanza secundaria educacion
## 1 Chachapoyas       27737 0.5467212  73.38709 62.7192982  9.968829
## 2      Cheto          608 0.3274366  77.83988 44.6136813  4.961860
## 3   Chiliquin         790 0.2115017  76.24811  8.0251613  4.439228
## 4 Asuncion            296 0.1683225  73.28082  0.7514946  6.079101
## 5    Balsas          1590 0.2633761  71.96708 14.4828735  5.282190
## 6  Magdalena          856 0.4012976  73.43866 36.7393695  6.271067
##   ingresos
## 1 866.5725
## 2 346.7647
## 3 258.5687
## 4 341.9903
## 5 340.2772
## 6 615.1609

Agregamos el nombre de la region Callao

IDHDISTRITOS[is.na(IDHDISTRITOS$nombreRegion),]$nombreRegion = "CALLAO"

Creamos una latente de IDH

library(psych)
## 
## Attaching package: 'psych'
## The following objects are masked from 'package:ggplot2':
## 
##     %+%, alpha
KMO(IDHDISTRITOS[,c(9:12)])
## Kaiser-Meyer-Olkin factor adequacy
## Call: KMO(r = IDHDISTRITOS[, c(9:12)])
## Overall MSA =  0.65
## MSA for each item = 
##  esperanza secundaria  educacion   ingresos 
##       0.90       0.69       0.60       0.67
cortest.bartlett(IDHDISTRITOS[,c(9:12)])$p.value<0.05
## R was not square, finding R from data
## [1] TRUE
library(GPArotation)
IDHlat=fa((IDHDISTRITOS[,c(9:12)]),
                1, #NUMERO DE FACTORES, ESTO PUEDE CAMBIAR
                rotate="oblimin", scores=T,
                cor="cor") #ESO PUEDE CAMBIAR DEPENDIENDO DEL TIPO DE VARIABLES. 
## Warning in fac(r = r, nfactors = nfactors, n.obs = n.obs, rotate =
## rotate, : A loading greater than abs(1) was detected. Examine the loadings
## carefully.
## The estimated weights for the factor scores are probably incorrect.  Try a different factor extraction method.
## Warning in fac(r = r, nfactors = nfactors, n.obs = n.obs, rotate =
## rotate, : An ultra-Heywood case was detected. Examine the results carefully
print(IDHlat,digits=2,cut = 0.2)
## Factor Analysis using method =  minres
## Call: fa(r = (IDHDISTRITOS[, c(9:12)]), nfactors = 1, rotate = "oblimin", 
##     scores = T, cor = "cor")
## 
##  Warning: A Heywood case was detected. 
## Standardized loadings (pattern matrix) based upon correlation matrix
##             MR1    h2    u2 com
## esperanza  0.31 0.096  0.90   1
## secundaria 0.71 0.511  0.49   1
## educacion  1.01 1.010 -0.01   1
## ingresos   0.80 0.638  0.36   1
## 
##                 MR1
## SS loadings    2.25
## Proportion Var 0.56
## 
## Mean item complexity =  1
## Test of the hypothesis that 1 factor is sufficient.
## 
## The degrees of freedom for the null model are  6  and the objective function was  1.99 with Chi Square of  3646.99
## The degrees of freedom for the model are 2  and the objective function was  0.05 
## 
## The root mean square of the residuals (RMSR) is  0.04 
## The df corrected root mean square of the residuals is  0.06 
## 
## The harmonic number of observations is  1834 with the empirical chi square  27.72  with prob <  9.6e-07 
## The total number of observations was  1834  with Likelihood Chi Square =  88.17  with prob <  7.1e-20 
## 
## Tucker Lewis Index of factoring reliability =  0.929
## RMSEA index =  0.153  and the 90 % confidence intervals are  0.127 0.181
## BIC =  73.14
## Fit based upon off diagonal values = 1
IDHSCORE=factor.scores((IDHDISTRITOS[,c(9:12)]),IDHlat)$scores
IDHDISTRITOS=merge(IDHDISTRITOS,IDHSCORE,
                 by.x=0,
                 by.y=0) # 'by.y=0' está usando los row.names

head(IDHDISTRITOS)
##   Row.names ubigeoRegion ubigeoProvincia ubigeoDistrito nombreRegion
## 1         1       010000          010100         010101     AMAZONAS
## 2        10       010000          010100         010116     AMAZONAS
## 3       100       020000          020300         020305       ANCASH
## 4      1000       110000          110500         110504          ICA
## 5      1001       110000          110500         110505          ICA
## 6      1002       110000          110500         110506          ICA
##    nombreProvincia                                 DISTRITO habitantes
## 1      Chachapoyas                             Chachapoyas       27737
## 2      Chachapoyas                                Olleros          370
## 3 Antonio Raymondi Mirgas                                         5366
## 4            Pisco Independencia                                 13727
## 5            Pisco Paracas                                        5722
## 6            Pisco San Andres                                    13524
##         IDH esperanza secundaria educacion ingresos        MR1
## 1 0.5467212  73.38709   62.71930  9.968829 866.5725  1.5207069
## 2 0.2574440  76.45172   20.26770  5.237085 256.4438 -0.6920420
## 3 0.1512524  71.58821   13.80350  4.520514 102.5497 -1.0437907
## 4 0.4125337  75.65267   58.94248  8.462404 424.8150  0.8223145
## 5 0.4997222  76.28161   52.98228 10.222032 677.0412  1.7433657
## 6 0.4765053  76.10384   69.27835 10.024492 529.3206  1.5922376
IDHDISTRITOS=IDHDISTRITOS[c(4,8,10:14)]
names(IDHDISTRITOS)=c("ubigeoDistrito","HABITANTES","ESPERANZA","SECUNDARIA","EDUCACION","INGRESOS","IDHLAT")

Variable IDE

Partidas de nacimiento en el registro civil
link="https://docs.google.com/spreadsheets/d/e/2PACX-1vS63wfOTNXPgUVUJvi17Xis_bBVodIGrjDQixrB-kNFFB-_o1Mq5yGjiZdTQoCf-nYw0YwbeNF-6oYi/pub?output=xlsx"

library(openxlsx)

PARTIDA=read.xlsx(link, 
                sheet = 1, #hoja que cargaremos, corresponde al año 2011. 
                startRow = 0, #desde esta fila empezaremos a leer, aseguremonos de no perder títulos
                skipEmptyRows = T, skipEmptyCols = T)

head(PARTIDA)
##   P:.Tiene.partida.de.nacimiento.del.Registro.Civil
## 1                                     AREA # 010101
## 2                                        Categorías
## 3                    Si tiene partida de nacimiento
## 4                    No tiene partida de nacimiento
## 5                                             Total
## 6                                        Ignorado :
##                                                       X2    X3          X4
## 1 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas  <NA>        <NA>
## 2                                                  Casos     % Acumulado %
## 3                                                23776.0 99.66       99.66
## 4                                                   82.0  0.34       100.0
## 5                                                23858.0 100.0       100.0
## 6                                                   81.0  <NA>        <NA>

Cambio nombre de columnas: -solo para identificarlas mejor-

names(PARTIDA) = c("ubigeoDistrito", "Distrito", "por", "acumulado")

Reviso las ultimas filas

tail(PARTIDA,10)
##                        ubigeoDistrito    Distrito   por   acumulado
## 10934  No tiene partida de nacimiento       364.0  9.79       100.0
## 10935                           Total      3719.0 100.0       100.0
## 10936                      Ignorado :        27.0  <NA>        <NA>
## 10937                         RESUMEN        <NA>  <NA>        <NA>
## 10938                      Categorías       Casos     % Acumulado %
## 10939  Si tiene partida de nacimiento  2.703648E7 98.98       98.98
## 10940  No tiene partida de nacimiento    277596.0  1.02       100.0
## 10941                           Total 2.7314076E7 100.0       100.0
## 10942                      Ignorado :     98081.0  <NA>        <NA>
## 10943          Fuente: INEI - CPV2007        <NA>  <NA>        <NA>

Elimino las ultimas filas -hacen referencia a todo el peru-

PARTIDA=PARTIDA[-c(10937:10943),]
tail((PARTIDA))
##                        ubigeoDistrito
## 10931                   AREA # 250401
## 10932                      Categorías
## 10933  Si tiene partida de nacimiento
## 10934  No tiene partida de nacimiento
## 10935                           Total
## 10936                      Ignorado :
##                                        Distrito   por   acumulado
## 10931 Dpto. Ucayali   Prov. Purus   Dist. Purus  <NA>        <NA>
## 10932                                     Casos     % Acumulado %
## 10933                                    3355.0 90.21       90.21
## 10934                                     364.0  9.79       100.0
## 10935                                    3719.0 100.0       100.0
## 10936                                      27.0  <NA>        <NA>

Distritos total:

distritos1=PARTIDA[grep("Dist", PARTIDA$Distrito),1:2] #solo quiero quedarme con la 1 y 2 columna
head(distritos1)
##    ubigeoDistrito                                               Distrito
## 1   AREA # 010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 7   AREA # 010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 13  AREA # 010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 19  AREA # 010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 25  AREA # 010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 31  AREA # 010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba

Manipulamos ubigeo para quedarnos solo con los codigos:

distritos1$ubigeoDistrito= substr(distritos1$ubigeoDistrito,8,14)

Vean el resultado:

head(distritos1)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 7          010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 13         010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 19         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 25         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 31         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba

No partida:

NOPARTIDA=as.data.frame(PARTIDA[grep("No", PARTIDA$ubigeoDistrito),2]) 
names(NOPARTIDA) = c("NOPARTIDAS")

Juntamos ambas data frames -no merge-:

data_partida = cbind(distritos1,NOPARTIDA)
head(data_partida)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 7          010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 13         010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 19         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 25         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 31         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba
##    NOPARTIDAS
## 1        82.0
## 7         2.0
## 13       34.0
## 19        0.0
## 25        1.0
## 31       23.0

Cambiamos a numerica. Como estaba como factor no cambia directo a numerica.

data_partida$NOPARTIDAS = as.numeric(as.character(data_partida$NOPARTIDAS))

Data final:

head(data_partida)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 7          010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 13         010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 19         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 25         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 31         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba
##    NOPARTIDAS
## 1          82
## 7           2
## 13         34
## 19          0
## 25          1
## 31         23

lo guardo a csv just in case:

write.csv(data_partida, "data_partida.csv")
SECUNDARIA
link="https://docs.google.com/spreadsheets/d/e/2PACX-1vTrWabDrAv6lTdmk6yPNsFICqOqtb_jpWGldSHj25GJF6XpjFDIt4l-n4HCjtskUvtEqyVzleobJMKw/pub?output=xlsx"

library(openxlsx)

SECUNDARIA=read.xlsx(link, 
                sheet = 1, #hoja que cargaremos, corresponde al año 2011. 
                startRow = 0, #desde esta fila empezaremos a leer, aseguremonos de no perder títulos
                skipEmptyRows = T, skipEmptyCols = T)

head(SECUNDARIA)
##   P3a+:.Ûltimo.nivel.de.estudios.que.aprobó
## 1                             AREA # 010101
## 2                                Categorías
## 3                                 Sin Nivel
## 4                         Educación Inicial
## 5                                  Primaria
## 6                                Secundaria
##                                                       X2    X3          X4
## 1 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas  <NA>        <NA>
## 2                                                  Casos     % Acumulado %
## 3                                                 1847.0  8.13        8.13
## 4                                                  622.0  2.74       10.87
## 5                                                 7049.0 31.04       41.91
## 6                                                 6580.0 28.98       70.89

Cambio nombre de columnas: -solo para identificarlas mejor-

names(SECUNDARIA) = c("ubigeoDistrito", "Distrito", "por", "acumulado")

Reviso las ultimas filas

tail(SECUNDARIA,15)
##                      ubigeoDistrito    Distrito   por   acumulado
## 21976                         Total      3352.0 100.0       100.0
## 21977                         NSA :       394.0  <NA>        <NA>
## 21978                       RESUMEN        <NA>  <NA>        <NA>
## 21979                    Categorías       Casos     % Acumulado %
## 21980                     Sin Nivel   2820935.0 10.93       10.93
## 21981             Educación Inicial    691494.0  2.68       13.61
## 21982                      Primaria   8087558.0 31.33       44.94
## 21983                    Secundaria   8287670.0 32.11       77.05
## 21984  Superior No Univ. incompleta   1289464.0   5.0       82.05
## 21985    Superior No Univ. completa   1582597.0  6.13       88.18
## 21986     Superior Univ. incompleta   1192157.0  4.62        92.8
## 21987       Superior Univ. completa   1858456.0   7.2       100.0
## 21988                         Total 2.5810331E7 100.0       100.0
## 21989                         NSA :   1601826.0  <NA>        <NA>
## 21990        Fuente: INEI - CPV2007        <NA>  <NA>        <NA>

Elimino las ultimas filas -hacen referencia a todo el peru-

SECUNDARIA=SECUNDARIA[-c(21978:21990),]
tail(SECUNDARIA,15)
##                      ubigeoDistrito
## 21963       Superior Univ. completa
## 21964                         Total
## 21965                         NSA :
## 21966                 AREA # 250401
## 21967                    Categorías
## 21968                     Sin Nivel
## 21969             Educación Inicial
## 21970                      Primaria
## 21971                    Secundaria
## 21972  Superior No Univ. incompleta
## 21973    Superior No Univ. completa
## 21974     Superior Univ. incompleta
## 21975       Superior Univ. completa
## 21976                         Total
## 21977                         NSA :
##                                        Distrito   por   acumulado
## 21963                                      39.0  0.71       100.0
## 21964                                    5491.0 100.0       100.0
## 21965                                     556.0  <NA>        <NA>
## 21966 Dpto. Ucayali   Prov. Purus   Dist. Purus  <NA>        <NA>
## 21967                                     Casos     % Acumulado %
## 21968                                     809.0 24.13       24.13
## 21969                                      98.0  2.92       27.06
## 21970                                    1211.0 36.13       63.19
## 21971                                     876.0 26.13       89.32
## 21972                                     110.0  3.28        92.6
## 21973                                     156.0  4.65       97.26
## 21974                                      32.0  0.95       98.21
## 21975                                      60.0  1.79       100.0
## 21976                                    3352.0 100.0       100.0
## 21977                                     394.0  <NA>        <NA>

Distritos total:

distritos1=SECUNDARIA[grep("Dist", SECUNDARIA$Distrito),1:2] #solo quiero quedarme con la 1 y 2 columna
head(distritos1) 
##    ubigeoDistrito                                               Distrito
## 1   AREA # 010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 13  AREA # 010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 24  AREA # 010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 36  AREA # 010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 48  AREA # 010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 60  AREA # 010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba

Manipulamos ubigeo para quedarnos solo con los codigos:

distritos1$ubigeoDistrito= substr(distritos1$ubigeoDistrito,8,14)

Vean el resultado:

head(distritos1)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 13         010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 24         010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 36         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 48         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 60         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba

No partida:

secundaria=as.data.frame(SECUNDARIA[grep("Secundaria", SECUNDARIA$ubigeoDistrito),2]) 
names(secundaria) = c("SECUNDARIA")

Juntamos ambas data frames -no merge-:

data_secundaria = cbind(distritos1,secundaria)
head(data_secundaria)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 13         010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 24         010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 36         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 48         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 60         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba
##    SECUNDARIA
## 1      6580.0
## 13       45.0
## 24      201.0
## 36       88.0
## 48       65.0
## 60      414.0

Cambiamos a numerica. Como estaba como factor no cambia directo a numerica.

data_secundaria$SECUNDARIA = as.numeric(as.character(data_secundaria$SECUNDARIA))

Data final:

head(data_secundaria)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 13         010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 24         010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 36         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 48         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 60         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba
##    SECUNDARIA
## 1        6580
## 13         45
## 24        201
## 36         88
## 48         65
## 60        414

lo guardo a csv just in case:

write.csv(data_secundaria, "data_secundaria.csv")
SERVICIO DE AGUA
link="https://docs.google.com/spreadsheets/d/e/2PACX-1vTFlG5NgBsykf_uxJ-vDarjtv5bfH76Kz1u9R0fE40FKicHxjMymhiNuFmCUS-tduMl8XmwKu0Wo0eq/pub?output=xlsx"

library(openxlsx)

AGUA=read.xlsx(link, 
                sheet = 1, #hoja que cargaremos, corresponde al año 2011. 
                startRow = 0, #desde esta fila empezaremos a leer, aseguremonos de no perder títulos
                skipEmptyRows = T, skipEmptyCols = T)

head(AGUA)
##   V:.Servicio.de.agua.-.Todos.los.días.de.la.semana
## 1                                     AREA # 010101
## 2                                        Categorías
## 3                         Si tiene servicio de agua
## 4                         No tiene servicio de agua
## 5                                             Total
## 6                                             NSA :
##                                                       X2    X3          X4
## 1 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas  <NA>        <NA>
## 2                                                  Casos     % Acumulado %
## 3                                                 5762.0 98.29       98.29
## 4                                                  100.0  1.71       100.0
## 5                                                 5862.0 100.0       100.0
## 6                                                 1449.0  <NA>        <NA>

Cambio nombre de columnas: -solo para identificarlas mejor-

names(AGUA) = c("ubigeoDistrito", "Distrito", "por", "acumulado")

Reviso las ultimas filas

tail(AGUA,10)
##                   ubigeoDistrito  Distrito   por   acumulado
## 10462  Si tiene servicio de agua       4.0 100.0       100.0
## 10463                      Total       4.0 100.0       100.0
## 10464                      NSA :     943.0  <NA>        <NA>
## 10465                    RESUMEN      <NA>  <NA>        <NA>
## 10466                 Categorías     Casos     % Acumulado %
## 10467  Si tiene servicio de agua 3878572.0 89.85       89.85
## 10468  No tiene servicio de agua  438127.0 10.15       100.0
## 10469                      Total 4316699.0 100.0       100.0
## 10470                      NSA : 3266441.0  <NA>        <NA>
## 10471     Fuente: INEI - CPV2007      <NA>  <NA>        <NA>

Elimino las ultimas filas -hacen referencia a todo el peru-

AGUA=AGUA[-c(10465:10471),]
tail(AGUA,10)
##                   ubigeoDistrito                                  Distrito
## 10455                 Categorías                                     Casos
## 10456  Si tiene servicio de agua                                     221.0
## 10457  No tiene servicio de agua                                       5.0
## 10458                      Total                                     226.0
## 10459                      NSA :                                    1553.0
## 10460              AREA # 250401 Dpto. Ucayali   Prov. Purus   Dist. Purus
## 10461                 Categorías                                     Casos
## 10462  Si tiene servicio de agua                                       4.0
## 10463                      Total                                       4.0
## 10464                      NSA :                                     943.0
##         por   acumulado
## 10455     % Acumulado %
## 10456 97.79       97.79
## 10457  2.21       100.0
## 10458 100.0       100.0
## 10459  <NA>        <NA>
## 10460  <NA>        <NA>
## 10461     % Acumulado %
## 10462 100.0       100.0
## 10463 100.0       100.0
## 10464  <NA>        <NA>

Distritos total:

distritos1=AGUA[grep("Dist", AGUA$Distrito),1:2] #solo quiero quedarme con la 1 y 2 columna
head(distritos1) 
##    ubigeoDistrito                                               Distrito
## 1   AREA # 010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 7   AREA # 010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 9   AREA # 010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 14  AREA # 010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 19  AREA # 010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 24  AREA # 010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba

Manipulamos ubigeo para quedarnos solo con los codigos:

distritos1$ubigeoDistrito= substr(distritos1$ubigeoDistrito,8,14)

Vean el resultado:

head(distritos1)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 7          010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 9          010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 14         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 19         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 24         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba

SI AGUA:

agua=as.data.frame(AGUA[grep("Si", AGUA$ubigeoDistrito),2]) 
names(agua) = c("agua")

Juntamos ambas data frames -no merge-:

data_agua = cbind(distritos1,agua)
head(data_agua)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 7          010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 9          010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 14         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 19         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 24         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba
##      agua
## 1  5762.0
## 7     0.0
## 9     8.0
## 14    6.0
## 19   36.0
## 24  284.0

Cambiamos a numerica. Como estaba como factor no cambia directo a numerica.

data_agua$agua = as.numeric(as.character(data_agua$agua))

Data final:

head(data_agua)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 7          010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 9          010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 14         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 19         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 24         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba
##    agua
## 1  5762
## 7     0
## 9     8
## 14    6
## 19   36
## 24  284

lo guardo a csv just in case:

write.csv(data_agua, "data_agua.csv")
ELECTRICIDAD
link="https://docs.google.com/spreadsheets/d/e/2PACX-1vRKVpRFZm4-NQE2BCDSY-esbALM6nDiDQ7kOfCSiuuGgcQQKe1rX06BOuvPUehBMMZnegucVpiiWpwQ/pub?output=xlsx"

library(openxlsx)

ELECTRICIDAD=read.xlsx(link, 
                sheet = 1, #hoja que cargaremos, corresponde al año 2011. 
                startRow = 0, #desde esta fila empezaremos a leer, aseguremonos de no perder títulos
                skipEmptyRows = T, skipEmptyCols = T)

head(ELECTRICIDAD)
##   V:.La.vivienda.tiene.alumbrado.eléctrico
## 1                            AREA # 010101
## 2                               Categorías
## 3             Si tiene alumbrado eléctrico
## 4             No tiene alumbrado eléctrico
## 5                                    Total
## 6                                    NSA :
##                                                       X2    X3          X4
## 1 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas  <NA>        <NA>
## 2                                                  Casos     % Acumulado %
## 3                                                 5790.0 90.89       90.89
## 4                                                  580.0  9.11       100.0
## 5                                                 6370.0 100.0       100.0
## 6                                                  941.0  <NA>        <NA>

Cambio nombre de columnas: -solo para identificarlas mejor-

names(ELECTRICIDAD) = c("ubigeoDistrito", "Distrito", "por", "acumulado")

Reviso las ultimas filas

tail(ELECTRICIDAD,10)
##                      ubigeoDistrito  Distrito   por   acumulado
## 10984  No tiene alumbrado eléctrico     498.0 67.66       100.0
## 10985                         Total     736.0 100.0       100.0
## 10986                         NSA :     211.0  <NA>        <NA>
## 10987                       RESUMEN      <NA>  <NA>        <NA>
## 10988                    Categorías     Casos     % Acumulado %
## 10989  Si tiene alumbrado eléctrico 4741730.0 74.09       74.09
## 10990  No tiene alumbrado eléctrico 1658401.0 25.91       100.0
## 10991                         Total 6400131.0 100.0       100.0
## 10992                         NSA : 1183009.0  <NA>        <NA>
## 10993        Fuente: INEI - CPV2007      <NA>  <NA>        <NA>

Elimino las ultimas filas -hacen referencia a todo el peru-

ELECTRICIDAD=ELECTRICIDAD[-c(10987:10993),]
tail(ELECTRICIDAD,10)
##                      ubigeoDistrito
## 10977  Si tiene alumbrado eléctrico
## 10978  No tiene alumbrado eléctrico
## 10979                         Total
## 10980                         NSA :
## 10981                 AREA # 250401
## 10982                    Categorías
## 10983  Si tiene alumbrado eléctrico
## 10984  No tiene alumbrado eléctrico
## 10985                         Total
## 10986                         NSA :
##                                        Distrito   por   acumulado
## 10977                                     313.0 22.52       22.52
## 10978                                    1077.0 77.48       100.0
## 10979                                    1390.0 100.0       100.0
## 10980                                     389.0  <NA>        <NA>
## 10981 Dpto. Ucayali   Prov. Purus   Dist. Purus  <NA>        <NA>
## 10982                                     Casos     % Acumulado %
## 10983                                     238.0 32.34       32.34
## 10984                                     498.0 67.66       100.0
## 10985                                     736.0 100.0       100.0
## 10986                                     211.0  <NA>        <NA>

Distritos total:

distritos1=ELECTRICIDAD[grep("Dist", ELECTRICIDAD$Distrito),1:2] #solo quiero quedarme con la 1 y 2 columna
head(distritos1) 
##    ubigeoDistrito                                               Distrito
## 1   AREA # 010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 7   AREA # 010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 13  AREA # 010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 19  AREA # 010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 25  AREA # 010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 31  AREA # 010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba

Manipulamos ubigeo para quedarnos solo con los codigos:

distritos1$ubigeoDistrito= substr(distritos1$ubigeoDistrito,8,14)

Vean el resultado:

head(distritos1)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 7          010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 13         010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 19         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 25         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 31         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba

SI ELECTRICIDAD:

electricidad=as.data.frame(ELECTRICIDAD[grep("Si", ELECTRICIDAD$ubigeoDistrito),2]) 
names(electricidad) = c("electricidad")

Juntamos ambas data frames -no merge-:

data_electricidad = cbind(distritos1,electricidad)
head(data_electricidad)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 7          010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 13         010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 19         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 25         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 31         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba
##    electricidad
## 1        5790.0
## 7          42.0
## 13        136.0
## 19        130.0
## 25        111.0
## 31        304.0

Cambiamos a numerica. Como estaba como factor no cambia directo a numerica.

data_electricidad$electricidad = as.numeric(as.character(data_electricidad$electricidad))

Data final:

head(data_electricidad)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 7          010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 13         010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 19         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 25         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 31         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba
##    electricidad
## 1          5790
## 7            42
## 13          136
## 19          130
## 25          111
## 31          304

lo guardo a csv just in case:

write.csv(data_electricidad, "data_electricidad.csv")
ESSALUD
link="https://docs.google.com/spreadsheets/d/e/2PACX-1vQSf5QPSe3ES8UlLARhfZAxy6YYD1b9icyunW5d-AO7fvu2HbeTI20u2yMW2aoqZNxIIoPG4bsBVWS4/pub?output=xlsx"

library(openxlsx)

ESSALUD=read.xlsx(link, 
                sheet = 1, #hoja que cargaremos, corresponde al año 2011. 
                startRow = 0, #desde esta fila empezaremos a leer, aseguremonos de no perder títulos
                skipEmptyRows = T, skipEmptyCols = T)

head(ESSALUD)
##    P:.Población.afiliada.a.seguros.de.salud
## 1                             AREA # 010101
## 2                                Categorías
## 3                Solo esta asegurado al SIS
## 4  Esta asegurado en el SIS, ESSALUD y Otro
## 5        Esta asegurado en el SIS y ESSALUD
## 6           Esta asegurado en el SIS y Otro
##                                                       X2   X3          X4
## 1 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas <NA>        <NA>
## 2                                                  Casos    % Acumulado %
## 3                                                 4238.0 17.7        17.7
## 4                                                    2.0 0.01       17.71
## 5                                                   14.0 0.06       17.77
## 6                                                   13.0 0.05       17.82

Cambio nombre de columnas: -solo para identificarlas mejor-

names(ESSALUD) = c("ubigeoDistrito", "Distrito", "por", "acumulado")

Reviso las ultimas filas

tail(ESSALUD,15)
##                                  ubigeoDistrito    Distrito   por
## 16136               Sólo esta asegurado en Otro        71.0   1.9
## 16137                    No tiene ningun seguro       865.0 23.09
## 16138                                     Total      3746.0 100.0
## 16139                                   RESUMEN        <NA>  <NA>
## 16140                                Categorías       Casos     %
## 16141                Solo esta asegurado al SIS   5051559.0 18.43
## 16142  Esta asegurado en el SIS, ESSALUD y Otro      2208.0  0.01
## 16143        Esta asegurado en el SIS y ESSALUD     12145.0  0.04
## 16144           Esta asegurado en el SIS y Otro      9867.0  0.04
## 16145          Esta asegurado en ESSALUD y Otro    139336.0  0.51
## 16146           Sólo esta asegurado en  ESSALUD   4766357.0 17.39
## 16147               Sólo esta asegurado en Otro   1617226.0   5.9
## 16148                    No tiene ningun seguro 1.5813459E7 57.69
## 16149                                     Total 2.7412157E7 100.0
## 16150                    Fuente: INEI - CPV2007        <NA>  <NA>
##         acumulado
## 16136       76.91
## 16137       100.0
## 16138       100.0
## 16139        <NA>
## 16140 Acumulado %
## 16141       18.43
## 16142       18.44
## 16143       18.48
## 16144       18.52
## 16145       19.02
## 16146       36.41
## 16147       42.31
## 16148       100.0
## 16149       100.0
## 16150        <NA>

Elimino las ultimas filas -hacen referencia a todo el peru-

ESSALUD=ESSALUD[-c(16139:16150),]
tail(ESSALUD,10)
##                          ubigeoDistrito
## 16129                             Total
## 16130                     AREA # 250401
## 16131                        Categorías
## 16132        Solo esta asegurado al SIS
## 16133   Esta asegurado en el SIS y Otro
## 16134  Esta asegurado en ESSALUD y Otro
## 16135   Sólo esta asegurado en  ESSALUD
## 16136       Sólo esta asegurado en Otro
## 16137            No tiene ningun seguro
## 16138                             Total
##                                        Distrito   por   acumulado
## 16129                                    6047.0 100.0       100.0
## 16130 Dpto. Ucayali   Prov. Purus   Dist. Purus  <NA>        <NA>
## 16131                                     Casos     % Acumulado %
## 16132                                    2418.0 64.55       64.55
## 16133                                       2.0  0.05        64.6
## 16134                                       2.0  0.05       64.66
## 16135                                     388.0 10.36       75.01
## 16136                                      71.0   1.9       76.91
## 16137                                     865.0 23.09       100.0
## 16138                                    3746.0 100.0       100.0

Distritos total:

distritos1=ESSALUD[grep("Dist", ESSALUD$Distrito),1:2] #solo quiero quedarme con la 1 y 2 columna
head(distritos1) 
##    ubigeoDistrito                                               Distrito
## 1   AREA # 010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 12  AREA # 010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 19  AREA # 010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 26  AREA # 010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 33  AREA # 010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 40  AREA # 010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba

Manipulamos ubigeo para quedarnos solo con los codigos:

distritos1$ubigeoDistrito= substr(distritos1$ubigeoDistrito,8,14)

Vean el resultado:

head(distritos1)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 12         010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 19         010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 26         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 33         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 40         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba

NO SEGURO:

essalud=as.data.frame(ESSALUD[grep("seguro", ESSALUD$ubigeoDistrito),2]) 
names(essalud) = c("noseguro")

Juntamos ambas data frames -no merge-:

data_seguro = cbind(distritos1,essalud)
head(data_seguro)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 12         010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 19         010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 26         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 33         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 40         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba
##    noseguro
## 1   11769.0
## 12    100.0
## 19    650.0
## 26    314.0
## 33    395.0
## 40    906.0

Cambiamos a numerica. Como estaba como factor no cambia directo a numerica.

data_seguro$noseguro = as.numeric(as.character(data_seguro$noseguro))

Data final:

head(data_seguro)
##    ubigeoDistrito                                               Distrito
## 1          010101 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chachapoyas
## 12         010102    Dpto. Amazonas   Prov. Chachapoyas   Dist. Asunción
## 19         010103      Dpto. Amazonas   Prov. Chachapoyas   Dist. Balsas
## 26         010104       Dpto. Amazonas   Prov. Chachapoyas   Dist. Cheto
## 33         010105   Dpto. Amazonas   Prov. Chachapoyas   Dist. Chiliquin
## 40         010106 Dpto. Amazonas   Prov. Chachapoyas   Dist. Chuquibamba
##    noseguro
## 1     11769
## 12      100
## 19      650
## 26      314
## 33      395
## 40      906

lo guardo a csv just in case:

write.csv(data_seguro, "data_seguro.csv")

Eliminamos las columnas que nombrem el distrito

data_partida=data_partida[-c(2)]

Eliminamos las columnas que nombrem el distrito

data_seguro=data_seguro[-c(2)]

Eliminamos las columnas que nombrem el distrito

data_secundaria=data_secundaria[-c(2)]

Eliminamos las columnas que nombrem el distrito

data_electricidad=data_electricidad[-c(2)]

Eliminamos las columnas que nombrem el distrito

data_agua=data_agua[-c(2)]

Empezamos a juntar nuestra data con todos nuestas variable para formar ide

merge1=merge(data_partida, data_seguro,by="ubigeoDistrito")
merge2=merge(merge1, data_electricidad,by="ubigeoDistrito")
merge3=merge(merge2, data_agua,by="ubigeoDistrito")
IDE=merge(merge3, data_secundaria,by="ubigeoDistrito")

Latente de IDE

library(psych)
KMO(IDE[,c(2:5)])
## Kaiser-Meyer-Olkin factor adequacy
## Call: KMO(r = IDE[, c(2:5)])
## Overall MSA =  0.76
## MSA for each item = 
##   NOPARTIDAS     noseguro electricidad         agua 
##         0.87         0.79         0.68         0.74
cortest.bartlett(IDE[,c(2,5)])$p.value<0.05
## R was not square, finding R from data
## [1] TRUE
library(GPArotation)
IDElat=fa((IDE[,c(2:5)]),
                1, #NUMERO DE FACTORES, ESTO PUEDE CAMBIAR
                rotate="oblimin", scores=T,
                cor="cor") #ESO PUEDE CAMBIAR DEPENDIENDO DEL TIPO DE VARIABLES. 
## The estimated weights for the factor scores are probably incorrect.  Try a different factor extraction method.
print(IDElat,digits=2,cut = 0.2)
## Factor Analysis using method =  minres
## Call: fa(r = (IDE[, c(2:5)]), nfactors = 1, rotate = "oblimin", scores = T, 
##     cor = "cor")
## Standardized loadings (pattern matrix) based upon correlation matrix
##               MR1   h2     u2 com
## NOPARTIDAS   0.78 0.61 0.3941   1
## noseguro     1.00 1.00 0.0043   1
## electricidad 0.99 0.99 0.0117   1
## agua         0.96 0.92 0.0835   1
## 
##                 MR1
## SS loadings    3.51
## Proportion Var 0.88
## 
## Mean item complexity =  1
## Test of the hypothesis that 1 factor is sufficient.
## 
## The degrees of freedom for the null model are  6  and the objective function was  7.82 with Chi Square of  14307.7
## The degrees of freedom for the model are 2  and the objective function was  2.82 
## 
## The root mean square of the residuals (RMSR) is  0.03 
## The df corrected root mean square of the residuals is  0.05 
## 
## The harmonic number of observations is  1833 with the empirical chi square  17.79  with prob <  0.00014 
## The total number of observations was  1833  with Likelihood Chi Square =  5151.71  with prob <  0 
## 
## Tucker Lewis Index of factoring reliability =  -0.081
## RMSEA index =  1.186  and the 90 % confidence intervals are  1.158 1.213
## BIC =  5136.68
## Fit based upon off diagonal values = 1
IDElat=factor.scores((IDE[,c(2:5)]),IDHlat)$scores
IDE =merge(IDE,IDElat,
                 by.x=0,
                 by.y=0) # 'by.y=0' está usando los row.names

head(IDE)
##   Row.names ubigeoDistrito NOPARTIDAS noseguro electricidad agua
## 1         1         010101         82    11769         5790 5762
## 2        10         010110         33     2102          588  755
## 3       100         020205          1      628          183  206
## 4      1000         110506         52     8883         2342 1781
## 5      1001         110507        138    12660         2975  214
## 6      1002         110508         96     8618         2043 2551
##   SECUNDARIA        MR1
## 1       6580  0.7588179
## 2        757 -0.4937708
## 3        250 -0.1544198
## 4       5092  0.1265061
## 5       6834  2.6850212
## 6       5613 -1.6151081
IDE=IDE[-c(1)]
names(IDE)
## [1] "ubigeoDistrito" "NOPARTIDAS"     "noseguro"       "electricidad"  
## [5] "agua"           "SECUNDARIA"     "MR1"
names(IDE)=c("ubigeoDistrito","NOPARTIDAS","NOSEGURO","ELECTRICIDAD","AGUA","SECUNDARIAIDE","IDELAT")

Variable de control

Variable canon

Link de la limpieza de Canon 2011

"http://rpubs.com/airam123/444816"
## [1] "http://rpubs.com/airam123/444816"

Cargamos la data CANON 2011

link="https://docs.google.com/spreadsheets/d/e/2PACX-1vTNCiAE3wfYKC_lsX92H_8IrA2bgN6t7vyRmm3gWbww-Ha3R0oFksIAr9tLE2o5bdD37N394Yr2X7Gd/pub?output=xlsx"

library(openxlsx)

CANON2011=read.xlsx(link, 
                sheet = 1, #hoja que cargaremos, corresponde al año 2011. 
                startRow = 0, #desde esta fila empezaremos a leer, aseguremonos de no perder títulos
                skipEmptyRows = T, skipEmptyCols = T)

head(CANON2011)
##                           MUNICIPALIDADES PIM2011 ubigeoDistrito
## 1     MUNICIPALIDAD DISTRITAL DE ASUNCION  120995         010102
## 2       MUNICIPALIDAD DISTRITAL DE BALSAS   55366         010103
## 3        MUNICIPALIDAD DISTRITAL DE CHETO  145448         010104
## 4    MUNICIPALIDAD DISTRITAL DE CHILIQUIN  154126         010105
## 5  MUNICIPALIDAD DISTRITAL DE CHUQUIBAMBA  200626         010106
## 6      MUNICIPALIDAD DISTRITAL DE GRANADA  450379         010107
CANON2011=CANON2011[-c(1)]
names(CANON2011)=c("CANON","ubigeoDistrito")

3.Aplicación del merge

MERGE

link="https://docs.google.com/spreadsheets/d/e/2PACX-1vRmFL4gFqlsqhj1sDTWTJWppQYbiNLzhorZdGuVDFUUnxSA9BgHbtVScUOs2b7H0cYuKr-Dl48CCN20/pub?output=xlsx"

library(openxlsx)

EQUIVALENCIA=read.xlsx(link, 
                sheet = 1, #hoja que cargaremos, corresponde al año 2011. 
                startRow = 0, #desde esta fila empezaremos a leer, aseguremonos de no perder títulos
                skipEmptyRows = T, skipEmptyCols = T)

head(EQUIVALENCIA)
##   UBIGEO_RENIEC UBIGEO_INEI Departamento   Provincia Distrito_reniec
## 1        010101      010101     Amazonas Chachapoyas     Chachapoyas
## 2        010102      010102     Amazonas Chachapoyas        Asunción
## 3        010103      010103     Amazonas Chachapoyas          Balsas
## 4        010104      010104     Amazonas Chachapoyas           Cheto
## 5        010105      010105     Amazonas Chachapoyas       Chiliquin
## 6        010106      010106     Amazonas Chachapoyas     Chuquibamba
##   Distrito_INEI
## 1   Chachapoyas
## 2      Asunción
## 3        Balsas
## 4         Cheto
## 5     Chiliquin
## 6   Chuquibamba
EQUIVALENCIA=EQUIVALENCIA[c(1,2)]
names(EQUIVALENCIA) = c("ubigeoRENIEC","ubigeoDistrito")
DATA_TOTAL=merge(IDHDISTRITOS, CANON2011,by="ubigeoDistrito")
DATA_TOTAL=merge(DATA_TOTAL,IDE,by="ubigeoDistrito")
VOTO=merge(EQUIVALENCIA, VOTO ,by="ubigeoRENIEC")
VOTO=VOTO[-c(1)]
DATA_TOTAL=merge(DATA_TOTAL,VOTO, by="ubigeoDistrito")
ANTESOLLANTA=merge(EQUIVALENCIA, ANTESOLLANTA ,by="ubigeoRENIEC")
ANTESOLLANTA=ANTESOLLANTA[-c(1)]
DURANTEOLLANTA=merge(EQUIVALENCIA, DURANTEOLLANTA ,by="ubigeoRENIEC")
DURANTEOLLANTA=DURANTEOLLANTA[-c(1)]
ANTESOLLANTA=merge(ANTESOLLANTA,DATA_TOTAL,by="ubigeoDistrito")
DURANTEOLLANTA=merge(DURANTEOLLANTA,DATA_TOTAL,by="ubigeoDistrito")

5.Análisis de regresión

Creamos una subdata ####Regresion ordinal

subdataANTES=ANTESOLLANTA[c(2,3,8,9,15,16)]
head(subdataANTES)
##   NUMEROCONFLICTOS HABITANTES     IDHLAT   CANON        IDELAT
## 1                1       1119 -0.4684639  154728 -0.0597187247
## 2                1      23820 -0.3712931 1538345 -4.3712868039
## 3                1       7604 -0.5783118  801885 -0.4416274842
## 4                1       9444 -0.6479363 1496572 -1.4689764250
## 5                5        944 -0.9116309  171359  0.0002263618
## 6                2       4816 -0.4988178 9049449 -0.3432499790
##       DISTRITO
## 1      HUANCAS
## 2        IMAZA
## 3 YAMBRASBAMBA
## 4    EL CENEPA
## 5 SAN JERONIMO
## 6       JANGAS
row.names(subdataANTES)=subdataANTES$DISTRITO
subdataANTES=subdataANTES[-6]

head(subdataANTES)
##              NUMEROCONFLICTOS HABITANTES     IDHLAT   CANON        IDELAT
## HUANCAS                     1       1119 -0.4684639  154728 -0.0597187247
## IMAZA                       1      23820 -0.3712931 1538345 -4.3712868039
## YAMBRASBAMBA                1       7604 -0.5783118  801885 -0.4416274842
## EL CENEPA                   1       9444 -0.6479363 1496572 -1.4689764250
## SAN JERONIMO                5        944 -0.9116309  171359  0.0002263618
## JANGAS                      2       4816 -0.4988178 9049449 -0.3432499790
library("oglmx")
## Loading required package: maxLik
## Loading required package: miscTools
## 
## Please cite the 'maxLik' package as:
## Henningsen, Arne and Toomet, Ott (2011). maxLik: A package for maximum likelihood estimation in R. Computational Statistics 26(3), 443-458. DOI 10.1007/s00180-010-0217-1.
## 
## If you have questions, suggestions, or comments regarding the 'maxLik' package, please use a forum or 'tracker' at maxLik's R-Forge site:
## https://r-forge.r-project.org/projects/maxlik/
model1=ologit.reg(NUMEROCONFLICTOS ~ .,
                  data = subdataANTES)
## Warning in model.response(mf, "numeric"): using type = "numeric" with a
## factor response will be ignored
summary(model1)
## Ordered Logit Regression 
## Log-Likelihood: -243.7135 
## No. Iterations: 6 
## McFadden's R2: 0.01564049 
## AIC: 507.4269 
##               Estimate  Std. error t value Pr(>|t|)  
## HABITANTES -1.8867e-06  2.9005e-06 -0.6505  0.51538  
## IDHLAT      1.9822e-01  1.4833e-01  1.3363  0.18144  
## CANON       6.0789e-09  2.8043e-09  2.1677  0.03018 *
## IDELAT     -8.5832e-02  7.7451e-02 -1.1082  0.26777  
## ----- Threshold Parameters -----
##                  Estimate Std. error t value  Pr(>|t|)    
## Threshold (1->2)  1.30160    0.14702  8.8531 < 2.2e-16 ***
## Threshold (2->3)  2.54064    0.21761 11.6754 < 2.2e-16 ***
## Threshold (3->4)  3.93643    0.39249 10.0295 < 2.2e-16 ***
## Threshold (4->5)  4.80852    0.58863  8.1691 3.108e-16 ***
## Threshold (5->7)  5.21734    0.71636  7.2831 3.261e-13 ***
## Threshold (7->8)  5.91436    1.00659  5.8756 4.213e-09 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(model1m=margins.oglmx(model1,ascontinuous = TRUE))
## Marginal Effects on Pr(Outcome==1)
##              Marg. Eff  Std. error t value Pr(>|t|)  
## HABITANTES  3.2142e-07  4.9239e-07  0.6528  0.51390  
## IDHLAT     -3.3770e-02  2.5050e-02 -1.3481  0.17763  
## CANON      -1.0356e-09  4.8146e-10 -2.1510  0.03147 *
## IDELAT      1.4623e-02  1.3119e-02  1.1146  0.26502  
## ------------------------------------ 
## Marginal Effects on Pr(Outcome==2)
##              Marg. Eff  Std. error t value Pr(>|t|)  
## HABITANTES -1.9112e-07  2.9387e-07 -0.6504  0.51546  
## IDHLAT      2.0080e-02  1.5113e-02  1.3287  0.18396  
## CANON       6.1578e-10  2.9670e-10  2.0754  0.03795 *
## IDELAT     -8.6947e-03  7.8784e-03 -1.1036  0.26976  
## ------------------------------------ 
## Marginal Effects on Pr(Outcome==3)
##              Marg. Eff  Std. error t value Pr(>|t|)  
## HABITANTES -9.4082e-08  1.4505e-07 -0.6486  0.51657  
## IDHLAT      9.8846e-03  7.5307e-03  1.3126  0.18932  
## CANON       3.0313e-10  1.5202e-10  1.9940  0.04615 *
## IDELAT     -4.2801e-03  3.9152e-03 -1.0932  0.27430  
## ------------------------------------ 
## Marginal Effects on Pr(Outcome==4)
##              Marg. Eff  Std. error t value Pr(>|t|)
## HABITANTES -2.0727e-08  3.3181e-08 -0.6247   0.5322
## IDHLAT      2.1777e-03  1.9130e-03  1.1384   0.2550
## CANON       6.6783e-11  4.3930e-11  1.5202   0.1285
## IDELAT     -9.4296e-04  9.5469e-04 -0.9877   0.3233
## ------------------------------------ 
## Marginal Effects on Pr(Outcome==5)
##              Marg. Eff  Std. error t value Pr(>|t|)
## HABITANTES -5.1420e-09  9.3534e-09 -0.5497   0.5825
## IDHLAT      5.4024e-04  6.6646e-04  0.8106   0.4176
## CANON       1.6568e-11  1.7888e-11  0.9262   0.3543
## IDELAT     -2.3393e-04  3.1155e-04 -0.7509   0.4527
## ------------------------------------ 
## Marginal Effects on Pr(Outcome==7)
##              Marg. Eff  Std. error t value Pr(>|t|)
## HABITANTES -5.1676e-09  9.4011e-09 -0.5497   0.5825
## IDHLAT      5.4293e-04  6.6988e-04  0.8105   0.4177
## CANON       1.6650e-11  1.7975e-11  0.9263   0.3543
## IDELAT     -2.3509e-04  3.1287e-04 -0.7514   0.4524
## ------------------------------------ 
## Marginal Effects on Pr(Outcome==8)
##              Marg. Eff  Std. error t value Pr(>|t|)
## HABITANTES -5.1850e-09  9.4349e-09 -0.5496   0.5826
## IDHLAT      5.4475e-04  6.7220e-04  0.8104   0.4177
## CANON       1.6706e-11  1.8032e-11  0.9265   0.3542
## IDELAT     -2.3588e-04  3.1352e-04 -0.7524   0.4518
subdataDURANTE=DURANTEOLLANTA[c(2,3,8,9,15:17)]
head(subdataDURANTE)
##   NUMEROCONFLICTOS HABITANTES      IDHLAT    CANON     IDELAT
## 1                1       9444 -0.64793635  1496572 -1.4689764
## 2                1      15474 -0.53915672   874521 -3.9261843
## 3                1       2405 -0.01095242  2712519 -0.3251023
## 4                3      70147  1.31491277 66151284 -1.3604745
## 5                1       4816 -0.49881783  9049449 -0.3432500
## 6                1       4650 -0.63041874  2705328 -0.6775682
##        DISTRITO OLLANTA1V
## 1     EL CENEPA 0.9906233
## 2  RIO SANTIAGO 0.8847136
## 3      HUANCHAY 0.4164103
## 4 INDEPENDENCIA 0.2642258
## 5        JANGAS 0.2774951
## 6     PARIACOTO 0.1692991
row.names(subdataDURANTE)=subdataDURANTE$DISTRITO
subdataDURANTE=subdataDURANTE[-6]

head(subdataDURANTE)
##               NUMEROCONFLICTOS HABITANTES      IDHLAT    CANON     IDELAT
## EL CENEPA                    1       9444 -0.64793635  1496572 -1.4689764
## RIO SANTIAGO                 1      15474 -0.53915672   874521 -3.9261843
## HUANCHAY                     1       2405 -0.01095242  2712519 -0.3251023
## INDEPENDENCIA                3      70147  1.31491277 66151284 -1.3604745
## JANGAS                       1       4816 -0.49881783  9049449 -0.3432500
## PARIACOTO                    1       4650 -0.63041874  2705328 -0.6775682
##               OLLANTA1V
## EL CENEPA     0.9906233
## RIO SANTIAGO  0.8847136
## HUANCHAY      0.4164103
## INDEPENDENCIA 0.2642258
## JANGAS        0.2774951
## PARIACOTO     0.1692991
library("oglmx")

model2=ologit.reg(NUMEROCONFLICTOS ~ .,
                  data = subdataDURANTE)
## Warning in model.response(mf, "numeric"): using type = "numeric" with a
## factor response will be ignored
summary(model2)
## Ordered Logit Regression 
## Log-Likelihood: -107.1821 
## No. Iterations: 7 
## McFadden's R2: 0.04444293 
## AIC: 232.3642 
##               Estimate  Std. error t value Pr(>|t|)   
## HABITANTES  2.1108e-06  6.8671e-06  0.3074 0.758557   
## IDHLAT      3.7928e-01  2.4242e-01  1.5646 0.117684   
## CANON       3.1514e-09  3.0255e-09  1.0416 0.297591   
## IDELAT     -3.0753e-01  1.1868e-01 -2.5912 0.009564 **
## OLLANTA1V  -9.7797e-03  9.7755e-01 -0.0100 0.992018   
## ----- Threshold Parameters -----
##                  Estimate Std. error t value  Pr(>|t|)    
## Threshold (1->2)  1.85367    0.50667  3.6586 0.0002536 ***
## Threshold (2->3)  3.05284    0.56439  5.4091 6.334e-08 ***
## Threshold (3->4)  4.81366    0.85324  5.6417 1.684e-08 ***
## Threshold (4->8)  5.51544    1.10791  4.9783 6.416e-07 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(model1m=margins.oglmx(model1,ascontinuous = TRUE))
## Marginal Effects on Pr(Outcome==1)
##              Marg. Eff  Std. error t value Pr(>|t|)  
## HABITANTES  3.2142e-07  4.9239e-07  0.6528  0.51390  
## IDHLAT     -3.3770e-02  2.5050e-02 -1.3481  0.17763  
## CANON      -1.0356e-09  4.8146e-10 -2.1510  0.03147 *
## IDELAT      1.4623e-02  1.3119e-02  1.1146  0.26502  
## ------------------------------------ 
## Marginal Effects on Pr(Outcome==2)
##              Marg. Eff  Std. error t value Pr(>|t|)  
## HABITANTES -1.9112e-07  2.9387e-07 -0.6504  0.51546  
## IDHLAT      2.0080e-02  1.5113e-02  1.3287  0.18396  
## CANON       6.1578e-10  2.9670e-10  2.0754  0.03795 *
## IDELAT     -8.6947e-03  7.8784e-03 -1.1036  0.26976  
## ------------------------------------ 
## Marginal Effects on Pr(Outcome==3)
##              Marg. Eff  Std. error t value Pr(>|t|)  
## HABITANTES -9.4082e-08  1.4505e-07 -0.6486  0.51657  
## IDHLAT      9.8846e-03  7.5307e-03  1.3126  0.18932  
## CANON       3.0313e-10  1.5202e-10  1.9940  0.04615 *
## IDELAT     -4.2801e-03  3.9152e-03 -1.0932  0.27430  
## ------------------------------------ 
## Marginal Effects on Pr(Outcome==4)
##              Marg. Eff  Std. error t value Pr(>|t|)
## HABITANTES -2.0727e-08  3.3181e-08 -0.6247   0.5322
## IDHLAT      2.1777e-03  1.9130e-03  1.1384   0.2550
## CANON       6.6783e-11  4.3930e-11  1.5202   0.1285
## IDELAT     -9.4296e-04  9.5469e-04 -0.9877   0.3233
## ------------------------------------ 
## Marginal Effects on Pr(Outcome==5)
##              Marg. Eff  Std. error t value Pr(>|t|)
## HABITANTES -5.1420e-09  9.3534e-09 -0.5497   0.5825
## IDHLAT      5.4024e-04  6.6646e-04  0.8106   0.4176
## CANON       1.6568e-11  1.7888e-11  0.9262   0.3543
## IDELAT     -2.3393e-04  3.1155e-04 -0.7509   0.4527
## ------------------------------------ 
## Marginal Effects on Pr(Outcome==7)
##              Marg. Eff  Std. error t value Pr(>|t|)
## HABITANTES -5.1676e-09  9.4011e-09 -0.5497   0.5825
## IDHLAT      5.4293e-04  6.6988e-04  0.8105   0.4177
## CANON       1.6650e-11  1.7975e-11  0.9263   0.3543
## IDELAT     -2.3509e-04  3.1287e-04 -0.7514   0.4524
## ------------------------------------ 
## Marginal Effects on Pr(Outcome==8)
##              Marg. Eff  Std. error t value Pr(>|t|)
## HABITANTES -5.1850e-09  9.4349e-09 -0.5496   0.5826
## IDHLAT      5.4475e-04  6.7220e-04  0.8104   0.4177
## CANON       1.6706e-11  1.8032e-11  0.9265   0.3542
## IDELAT     -2.3588e-04  3.1352e-04 -0.7524   0.4518

6.Mapas

Mapas

folder='distritos'
fileName='DISTRITOS.shp' # nivel 2 son provincias
fileToRead=file.path(folder,fileName)

library(rgdal)
## Loading required package: sp
## rgdal: version: 1.3-6, (SVN revision 773)
##  Geospatial Data Abstraction Library extensions to R successfully loaded
##  Loaded GDAL runtime: GDAL 2.2.3, released 2017/11/20
##  Path to GDAL shared files: C:/Users/AIRAM/Documents/R/win-library/3.5/rgdal/gdal
##  GDAL binary built with GEOS: TRUE 
##  Loaded PROJ.4 runtime: Rel. 4.9.3, 15 August 2016, [PJ_VERSION: 493]
##  Path to PROJ.4 shared files: C:/Users/AIRAM/Documents/R/win-library/3.5/rgdal/proj
##  Linking to sp version: 1.3-1
PeruDistrito<- rgdal::readOGR(fileToRead,stringsAsFactors=FALSE)
## OGR data source with driver: ESRI Shapefile 
## Source: "C:\Users\AIRAM\Documents\estadistica 2\distritos\DISTRITOS.shp", layer: "DISTRITOS"
## with 1874 features
## It has 4 fields
subdata1=ANTESOLLANTA[c(2,16)]
MAPA1=merge(PeruDistrito,subdata1,by.x='DISTRITO',by.y="DISTRITO",all.x=T)

Pintamos el mapa de cuerdo a la cantidad de conflictos por distrito antes del gobierno de Ollanta

paleta=c("#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704") #colores
plot(MAPA1,col="#fff5eb",border=NA) 
plot(MAPA1,
     col=paleta[MAPA1$NUMEROCONFLICTOS],
     border=NA,add=T)

legend("right",
       title=
           
          "NUMERO DE CONFLICTOS 
          ANTES DEL GOBIERNO 
          DE OLLANTA",
       legend=c("1","2","3","4","5","6","7","8"),
       fill=paleta, cex=0.8,bty= "n" )

subdata2=DURANTEOLLANTA[c(2,16)]
MAPA2=merge(PeruDistrito,subdata2,by.x='DISTRITO',by.y="DISTRITO",all.x=T)
paleta=c("#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026") #colores
plot(MAPA2,col="#ffffcc",border=NA) 
plot(MAPA2,
     col=paleta[MAPA2$NUMEROCONFLICTOS],
     border=NA,add=T)

legend("right",
       title="NUMERO DE CONFLICTOS 
       DURANTE EL GOBIERNO 
       DE OLLANTA",
       legend=c("1","2","3","4","5","6","7","8"),
       fill=paleta, cex=0.9,bty= "n" )