Librerias
library(foreign)
library(dplyr)
library(spdep)
library(tigris)
library(rgeoda)
library(RColorBrewer)
library(viridis)
library(ggplot2)
library(tmap)
library(sf)
library(sp)
library(readxl)
library(tidyr)
Situación Problema A
El nearshoring “relocalización de proyectos de negocios”, “se refiere a una estrategia en que las empresas buscan reconfigurar sus cadenas de valor, haciéndolas más cortas y acercando los centros de producción con los mercados finales”. Con base en dicha definición, la localización geográfica y cercanía con el mercado de Estados Unidos representa para México una ventaja estratégica para la atracción de proyectos de inversión nearshoring. ¿Cuál es la tendencia actual del nearshoring para el caso de México? ¿Cómo es la distribución de flujos de inversión extranjera directa (IED) entre los estados de México? ¿Existen un patrón espacial y/o regional de la distribución de la IED durante los últimos años? ¿Qué tipo de características de los estados serían atractivas para la atracción de IED? ¿Se justifica el uso de un análisis espacial de datos para la predicción del nearshoring?
1) Brevemente, describir con sus propias palabras qué es un ESDA y cuál es su principal propósito en el proceso de analítica de datos.
El ESDA (Exploratory Spatial Data Analysis) es un tipo de análisis exploratorio, primero definamos el concepto base : EDA. El Análisis Exploratorio de Datos (EDA) es un proceso fundamental en la analítica de datos. Su principal propósito es comprender la naturaleza de los datos, identificar patrones, valores atípicos y relaciones antes de realizar un análisis más profundo.Este proceso implica inspeccionar, limpiar, transformar y modelar bases de datos. Su principal objetivo es descubrir información útil, llegar a conclusiones y respaldar la toma de decisiones.
Ahora bien, un ESDA es una técnica basada en la ciencia de la información geográfica (GIS) que permite describir y visualizar distribuciones espaciales. Su objetivo principal es dentificar ubicaciones atípicas o valores extremos en el espacio así como descubrir patrones de asociación espacial, agrupamientos o hot spots que puedan ser representados de manera numérica y visual a través de varios métodos.
2) Brevemente, describir con sus propias palabras el concepto de autocorrelación espacial así como 1-2 ejemplos relacionados con dicho concepto.
La autocorrelación es una característica de los datos que muestra el grado de similitud entre los valores de las mismas variables en intervalos de tiempo sucesivos. En contraste, la autocorrelación espacial se refiere a la similitud espacial entre los valores de una variable en un conjunto de datos geográfico. En otras palabras, busca patrones de dependencia espacial. Si los valores similares tienden a agruparse o dispersarse en el espacio, estamos hablando de autocorrelación espacial.
Esta característica se mide a través del Índice de Moran (I de Moran).
Si el índice es cercano a +1, hay autocorrelación espacial positiva:
Los valores similares se agrupan en el espacio.
Ejemplo: Temperaturas altas cerca de otras temperaturas altas.
Si el índice es cercano a -1, hay autocorrelación espacial negativa:
Los valores disímiles se agrupan.
Ejemplo: Áreas densamente pobladas rodeadas de áreas poco pobladas.
Este fenómeno se puede apreciar en la siguiente imágen:
3) Con base en el archivo de datos asignado realizar selección de variables y elaborar ESDA que incluye:
Importing dataset
covid <- read_excel("cross_sectional_dataset.xlsx")
covid[sapply(covid, is.numeric)] <- lapply(covid[sapply(covid, is.numeric)], function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x))
Importing shapefile
# Mexico's states (32)
mx_state_map <- st_read("C:/Users/maxca/Documents/Planación estratégica/Modulo 1/Actividades/mx_maps/mx_states/mexlatlong.shp")
## Reading layer `mexlatlong' from data source
## `C:\Users\maxca\Documents\Planación estratégica\Modulo 1\Actividades\mx_maps\mx_states\mexlatlong.shp'
## using driver `ESRI Shapefile'
## Simple feature collection with 32 features and 19 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -118.4042 ymin: 14.55055 xmax: -86.73862 ymax: 32.71846
## Geodetic CRS: WGS 84
# Mexico's Municipios (2,457)
mx_mpio_map <- st_read("C:/Users/maxca/Documents/Planación estratégica/Modulo 1/Actividades/mx_maps/mx_mpios/Mexican Municipalities.shp")
## Reading layer `Mexican Municipalities' from data source
## `C:\Users\maxca\Documents\Planación estratégica\Modulo 1\Actividades\mx_maps\mx_mpios\Mexican Municipalities.shp'
## using driver `ESRI Shapefile'
## Simple feature collection with 2456 features and 3 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -118.4076 ymin: 14.5321 xmax: -86.71041 ymax: 32.71865
## Geodetic CRS: WGS 84
# merging dataset
#mpio_geodata <- geo_join(mx_mpio_map,covid,'IDUNICO','clave_municipio',how='inner')
mpio_geodata <- inner_join(mx_mpio_map, covid, by = c("IDUNICO" = "clave_municipio"))
a. Estadísticos Descripitvos (Global y Regional). Incluir elementos gráficos (histogramas, gráfico de barras, etc.).
str(covid[,4:21])
## tibble [2,457 × 18] (S3: tbl_df/tbl/data.frame)
## $ numero_hospitales : num [1:2457] 1289 22 50 8 60 ...
## $ poblacion_2022 : num [1:2457] 961977 50864 60760 16918 130184 ...
## $ hogrem2015 : num [1:2457] 4.82 12.87 25.85 14.29 5.72 ...
## $ hogremjefmuj2015 : num [1:2457] 27.8 22.1 25.6 21.2 19.9 ...
## $ popnoafmed2015 : num [1:2457] 14.34 5.77 9.97 5.28 14.02 ...
## $ gini2015 : num [1:2457] 0.392 0.37 0.375 0.37 0.402 0.389 0.396 0.418 0.371 0.37 ...
## $ popden2020 : num [1:2457] 812 94.1 62.5 131.9 260.3 ...
## $ crimen_2018 : num [1:2457] 7.36 7.81 8.4 17.86 5.14 ...
## $ crimen_2019 : num [1:2457] 8.15 5.78 8.31 0 10.98 ...
## $ inclusion_fin_2019 : num [1:2457] 1.78 0 1.16 0 0.36 1.2 1.03 0 0 0 ...
## $ porcentaje_pob_pobreza : num [1:2457] 23.7 40.1 45.8 37 26.3 ...
## $ porcentaje_pob_pobreza_ext : num [1:2457] 1.97 4.14 4.5 3.38 3.29 2.88 5.56 2.32 3.15 4.81 ...
## $ porcentaje_pob_servicios_salud: num [1:2457] 20 16.5 21 17.6 21.1 ...
## $ porcentaje_pob_acceso_ss : num [1:2457] 37.8 62.1 76.2 47.5 41.9 ...
## $ pob_6-14_no_edu : num [1:2457] 4.6 6.29 6.95 5.7 5.88 4.44 4.38 5.74 5.37 4.4 ...
## $ rezago_social : num [1:2457] -1.32 -0.86 -0.92 -1 -1.17 -1.17 -1.07 -0.96 -0.9 -0.83 ...
## $ grado_rs : chr [1:2457] "Muy bajo" "Muy bajo" "Muy bajo" "Muy bajo" ...
## $ feb_2020 : num [1:2457] 0 0 0 0 0 0 0 0 0 0 ...
summary(covid[,4:21])
## numero_hospitales poblacion_2022 hogrem2015 hogremjefmuj2015
## Min. : 1.00 Min. : 95 Min. : 0.000 Min. : 0.00
## 1st Qu.: 3.00 1st Qu.: 4546 1st Qu.: 2.296 1st Qu.:22.15
## Median : 8.00 Median : 14240 Median : 5.357 Median :26.02
## Mean : 47.34 Mean : 52158 Mean : 8.562 Mean :25.86
## 3rd Qu.: 24.00 3rd Qu.: 37628 3rd Qu.:11.934 3rd Qu.:29.51
## Max. :2744.00 Max. :1815551 Max. :52.027 Max. :48.24
## popnoafmed2015 gini2015 popden2020 crimen_2018
## Min. : 1.124 Min. :0.3030 Min. : 0.16 Min. : 0.00
## 1st Qu.: 9.746 1st Qu.:0.3690 1st Qu.: 17.79 1st Qu.: 0.00
## Median :13.702 Median :0.3870 Median : 52.85 Median : 9.77
## Mean :14.938 Mean :0.3916 Mean : 313.09 Mean : 19.03
## 3rd Qu.:19.224 3rd Qu.:0.4100 3rd Qu.: 145.07 3rd Qu.: 25.61
## Max. :62.101 Max. :0.6400 Max. :56489.74 Max. :719.42
## crimen_2019 inclusion_fin_2019 porcentaje_pob_pobreza
## Min. : 0.00 Min. : 0.0000 Min. : 5.45
## 1st Qu.: 0.00 1st Qu.: 0.0000 1st Qu.:45.61
## Median : 11.54 Median : 0.0000 Median :62.43
## Mean : 20.34 Mean : 0.4892 Mean :61.91
## 3rd Qu.: 26.89 3rd Qu.: 0.8500 3rd Qu.:80.13
## Max. :551.82 Max. :10.6800 Max. :99.65
## porcentaje_pob_pobreza_ext porcentaje_pob_servicios_salud
## Min. : 0.00 Min. : 1.05
## 1st Qu.: 5.36 1st Qu.:16.10
## Median :12.52 Median :23.30
## Mean :17.14 Mean :25.10
## 3rd Qu.:24.06 3rd Qu.:32.81
## Max. :84.45 Max. :83.86
## porcentaje_pob_acceso_ss pob_6-14_no_edu rezago_social
## Min. :22.03 Min. : 0.000 Min. :-1.550000
## 1st Qu.:64.45 1st Qu.: 4.170 1st Qu.:-0.760000
## Median :76.39 Median : 5.730 Median :-0.220000
## Mean :72.37 Mean : 6.301 Mean :-0.004418
## 3rd Qu.:83.43 3rd Qu.: 7.770 3rd Qu.: 0.460000
## Max. :96.99 Max. :38.560 Max. : 6.830000
## grado_rs feb_2020
## Length:2457 Min. :0.000000
## Class :character 1st Qu.:0.000000
## Mode :character Median :0.000000
## Mean :0.003267
## 3rd Qu.:0.000000
## Max. :1.000000
hist(covid$numero_hospitales,main = 'Número de hospitales')
hist(covid$poblacion_2022,main = 'Población 2022')
hist(covid$gini2015,main = 'Coeficiente de desigualdad del ingreso')
hist(covid$crimen_2019 ,main = 'Crimen 2019')
# Gráfico de barras de la tasa de COVID19
ggplot(data = covid, aes(x = entidad, y = tasa_covid)) +
geom_bar(stat = "identity", fill = "skyblue") +
labs(title = "Tasa de COVID19 por Entidad",
x = "Entidad",
y = "Tasa de COVID19") +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
# Gráfico de barras de población 2022
ggplot(data = covid, aes(x = reorder(entidad, -poblacion_2022), y = poblacion_2022)) +
geom_bar(stat = "identity", fill = "lightgreen") +
labs(title = "Población por Entidad en 2022",
x = "Entidad",
y = "Población") +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
# Calcular estadísticos descriptivos por municipio
municipio_stats <- covid %>%
group_by(mpio) %>%
summarise(
promedio_hospitales = mean(numero_hospitales, na.rm = TRUE),
promedio_poblacion = mean(poblacion_2022, na.rm = TRUE),
total_casos = sum(total_casos, na.rm = TRUE),
tasa_covid = mean(tasa_covid, na.rm = TRUE)
)
# Mostrar los primeros registros de estadísticos por municipio
head(municipio_stats)
## # A tibble: 6 × 5
## mpio promedio_hospitales promedio_poblacion total_casos tasa_covid
## <chr> <dbl> <dbl> <dbl> <dbl>
## 1 Abala 2 7035 75 107.
## 2 Abasolo 16.2 28099. 1193 141.
## 3 Abejones 2 1033 21 203.
## 4 Acacoyagua 10 19856 26 13.1
## 5 Acajete 30 39104. 335 43.7
## 6 Acala 20 34494 47 13.6
# Mapa básico de municipios
tm_shape(mx_mpio_map) +
tm_polygons(col = "black") +
tm_compass(position=c("left","bottom")) +
tm_layout(main.title = "Mexico's Municipios")
b. Estadísticos de Dispersión (Global y Regional). Incluir elementos gráficos (box plots, qq plots, etc.).
# Gráfico de dispersión de población y tasa de COVID19
ggplot(data = municipio_stats, aes(x = promedio_poblacion, y = tasa_covid)) +
geom_point(color = "red") +
labs(title = "Relación entre Población y Tasa de COVID19 por Municipio",
x = "Población",
y = "Tasa de COVID19")
qqplot(covid$numero_hospitales,covid$total_casos,main = "Número de hospitales")
qqplot(covid$poblacion_2022,covid$total_casos, main = "Población 2022")
qqplot(covid$gini2015,covid$total_casos, main = "Coeficiente de Desigualdad de Género")
qqplot(covid$crimen_2019,covid$total_casos, main = "Tasa de crimen por cada 100 mil habitantes")
c. Visualizar la distribución espacial de las variables seleccionadas usando mapas.
tm_shape(mpio_geodata) +
tm_polygons(col = "tasa_covid", palette="-cividis", style="quantile", n=8, title="Tasa Covid") +
tm_layout(main.title= 'Tasa Covid por Municipios', title.position = c('right', 'top'), legend.position= c("left", "bottom"), title.size = 1)
tm_shape(mpio_geodata) +
tm_polygons(col = "total_casos", palette = "OrRd", style="quantile", n=8, title="Total de casos") +
tm_layout(main.title= 'Total de casos por municipio', title.position = c('right', 'top'), legend.position= c("left", "bottom"), title.size = 1)
tm_shape(mpio_geodata) +
tm_polygons(col = "numero_hospitales", palette="Purples", style="quantile", n=8, title="Tasa Covid") +
tm_layout(main.title= 'Número de Hospitales por municipio', title.position = c('right', 'top'), legend.position= c("left", "bottom"), title.size = 1)
tm_shape(mpio_geodata) +
tm_polygons(col = "poblacion_2022", palette="Greens", style="quantile", n=8, title="Tasa Covid") +
tm_layout(main.title= 'Población por municipio', title.position = c('right', 'top'), legend.position= c("left", "bottom"), title.size = 1)
tm_shape(mpio_geodata) +
tm_polygons(col = "gini2015", palette="inferno", style="quantile", n=8, title="Tasa Covid") +
tm_layout(main.title= 'Coeficiente de desigualdad del ingreso', title.position = c('right', 'top'), legend.position= c("left", "bottom"), title.size = 1)
tm_shape(mpio_geodata) +
tm_polygons(col = "crimen_2019", palette="viridis", style="quantile", n=8, title="Tasa Covid") +
tm_layout(main.title= 'Tasa de Crimen por Municipio', title.position = c('right', 'top'), legend.position= c("left", "bottom"), title.size = 1)
# Municipios de México - Graficación de variables
hospitales <- tm_shape(mpio_geodata) +
tm_polygons(col = "numero_hospitales", palette="Blues", style="quantile", n=8, title="Numero de Hospitales") +
tm_layout(main.title= 'Número de hospitales', title.position = c('right', 'top'), legend.position= c("left", "bottom"), title.size = 1)
## tm_polygons: Deprecated tmap v3 code detected. Code translated to v4
## Warning: The 'main.title' argument of 'tm_layout()' is deprecated as of tmap
## 4.0. Please use 'tm_title()' instead.
tasa_covid <- tm_shape(mpio_geodata) +
tm_polygons(col = "tasa_covid", palette="BuGn", style="quantile", n=8, title="Tasa Covid") +
tm_layout(main.title= 'Tasa Covid', title.position = c('right', 'top'), legend.position= c("left", "bottom"), title.size = 1)
## tm_polygons: Deprecated tmap v3 code detected. Code translated to v4
## Warning: The 'main.title' argument of 'tm_layout()' is deprecated as of tmap
## 4.0. Please use 'tm_title()' instead.
gini <- tm_shape(mpio_geodata) +
tm_polygons(col = "gini2015", palette="OrRd", style="quantile", n=8, title="gini2015") +
tm_layout(main.title= 'Gini 2015', title.position = c('right', 'top'), legend.position= c("left", "bottom"), title.size = 1)
## tm_polygons: Deprecated tmap v3 code detected. Code translated to v4
## Warning: The 'main.title' argument of 'tm_layout()' is deprecated as of tmap
## 4.0. Please use 'tm_title()' instead.
pop <- tm_shape(mpio_geodata) +
tm_polygons(col = "poblacion_2022", palette="-viridis", style="quantile", n=8, title="poblacion_2022") +
tm_layout(main.title= 'poblacion_2022', title.position = c('right', 'top'), legend.position= c("left", "bottom"), title.size = 1)
## tm_polygons: Deprecated tmap v3 code detected. Code translated to v4
## Warning: The 'main.title' argument of 'tm_layout()' is deprecated as of tmap
## 4.0. Please use 'tm_title()' instead.
# Panel of Maps
tmap_arrange(hospitales,tasa_covid,gini,pop, ncol = 2)
d. Elaborar y visualizar 1 – 2 matrices de connectividad para estados / municipios de México.
Spatial Connectivity Matrix
swm <- poly2nb(mx_mpio_map, queen=T)
summary(swm) # The average number of neighbors is 4.31
## Neighbour list object:
## Number of regions: 2456
## Number of nonzero links: 14392
## Percentage nonzero weights: 0.2385967
## Average number of links: 5.859935
## Link number distribution:
##
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 19 20 22
## 8 63 202 393 515 467 317 233 143 52 27 15 5 4 3 3 1 1 1 3
## 8 least connected regions:
## 300 355 668 859 931 1244 1462 2235 with 1 link
## 3 most connected regions:
## 967 1059 1174 with 22 links
Queen Matrix
sswm <- nb2listw(swm, style="W", zero.policy = TRUE)
mx_mpio_map_a <- as(mx_mpio_map, "Spatial")
mx_mpio_map_centroid <- coordinates(mx_mpio_map_a)
plot(mx_mpio_map_a,border="blue",axes=FALSE,las=1, main="Mexico's Municipality Queen SWM")
plot(mx_mpio_map_a,col="grey",border=grey(0.9),axes=T,add=T)
plot(sswm,coords=mx_mpio_map_centroid,pch=19,cex=0.1,col="red",add=T)
e. Detectar la presencia de autocorrelación espacial global para cada una de las variables seleccionadas.
f. Detectar la presencia de autocorrelación espacial local para cada una de las variables seleccionadas.
### Spatial Autocorrelation
# Global Moran's I
moran.test(mpio_geodata$numero_hospitales, sswm)
##
## Moran I test under randomisation
##
## data: mpio_geodata$numero_hospitales
## weights: sswm
##
## Moran I statistic standard deviate = 15.167, p-value < 2.2e-16
## alternative hypothesis: greater
## sample estimates:
## Moran I statistic Expectation Variance
## 0.1810738904 -0.0004073320 0.0001431794
moran.test(mpio_geodata$total_casos, sswm)
##
## Moran I test under randomisation
##
## data: mpio_geodata$total_casos
## weights: sswm
##
## Moran I statistic standard deviate = 35.138, p-value < 2.2e-16
## alternative hypothesis: greater
## sample estimates:
## Moran I statistic Expectation Variance
## 0.4143086184 -0.0004073320 0.0001392969
moran.test(mpio_geodata$crimen_2019, sswm)
##
## Moran I test under randomisation
##
## data: mpio_geodata$crimen_2019
## weights: sswm
##
## Moran I statistic standard deviate = 20.352, p-value < 2.2e-16
## alternative hypothesis: greater
## sample estimates:
## Moran I statistic Expectation Variance
## 0.2447673979 -0.0004073320 0.0001451252
moran.test(mpio_geodata$gini2015, sswm)
##
## Moran I test under randomisation
##
## data: mpio_geodata$gini2015
## weights: sswm
##
## Moran I statistic standard deviate = 24.283, p-value < 2.2e-16
## alternative hypothesis: greater
## sample estimates:
## Moran I statistic Expectation Variance
## 0.2954305305 -0.0004073320 0.0001484178
moran.test(mpio_geodata$poblacion_2022, sswm)
##
## Moran I test under randomisation
##
## data: mpio_geodata$poblacion_2022
## weights: sswm
##
## Moran I statistic standard deviate = 26.255, p-value < 2.2e-16
## alternative hypothesis: greater
## sample estimates:
## Moran I statistic Expectation Variance
## 0.3159585568 -0.0004073320 0.0001451961
table <- data.frame(Variable = c("numero_hospitales", "total_casos", "crimen_2019","gini_2015","poblacion_2022"), GM = c(0.18, 0.41, 0.24,0.29,0.31), Significance = c("*","***","**","**","***"))
table
## Variable GM Significance
## 1 numero_hospitales 0.18 *
## 2 total_casos 0.41 ***
## 3 crimen_2019 0.24 **
## 4 gini_2015 0.29 **
## 5 poblacion_2022 0.31 ***
mpio_geodata$sp_lag_numero_hospitales <- lag.listw(sswm, mpio_geodata$numero_hospitales, zero.policy=TRUE)
mpio_geodata$sp_lag_tasa_covid <- lag.listw(sswm, mpio_geodata$total_casos, zero.policy=TRUE)
mpio_geodata$sp_lag_crimen_2019 <- lag.listw(sswm, mpio_geodata$crimen_2019, zero.policy=TRUE)
mpio_geodata$sp_lag_gini2015 <- lag.listw(sswm, mpio_geodata$gini2015, zero.policy=TRUE)
mpio_geodata$sp_lag_poblacion_2022 <- lag.listw(sswm, mpio_geodata$poblacion_2022, zero.policy=TRUE)
g. Identificar la posible presencia de clústers locales / regionales para cada una de las variables de seleccionadas. ¿Cuáles son algunas de las características socioeconómicas y/o económicas de los estados / municipios que componen los clústers identificados?
newhosp_lag <- tm_shape(mpio_geodata) +
tm_polygons(col = "sp_lag_numero_hospitales", palette="Purples", style="quantile", n=5, title="Número de Hospitales") +
tm_layout(main.title= 'Clusters de Hospitales', title.position = c('right', 'top'), legend.position= c("left", "bottom"), title.size = 1)
## tm_polygons: Deprecated tmap v3 code detected. Code translated to v4
## Warning: The 'main.title' argument of 'tm_layout()' is deprecated as of tmap
## 4.0. Please use 'tm_title()' instead.
newhosp_lag
newcrime_lag <- tm_shape(mpio_geodata) +
tm_polygons(col = "sp_lag_crimen_2019", palette="Reds", style="quantile", n=10, title="Número de Crimen") +
tm_layout(main.title= 'Clusters de Crimen', title.position = c('right', 'top'), legend.position= c("left", "bottom"), title.size = 1)
## tm_polygons: Deprecated tmap v3 code detected. Code translated to v4
## Warning: The 'main.title' argument of 'tm_layout()' is deprecated as of tmap
## 4.0. Please use 'tm_title()' instead.
newcrime_lag
newgini_lag <- tm_shape(mpio_geodata) +
tm_polygons(col = "sp_lag_gini2015", palette="Blues", style="quantile", n=5, title="Desigualdad de ingreso") +
tm_layout(main.title= 'Clusters de Desigualdad de ingreso', title.position = c('right', 'top'), legend.position= c("left", "bottom"), title.size = 1)
## tm_polygons: Deprecated tmap v3 code detected. Code translated to v4
## Warning: The 'main.title' argument of 'tm_layout()' is deprecated as of tmap
## 4.0. Please use 'tm_title()' instead.
newgini_lag
newpob_lag <- tm_shape(mpio_geodata) +
tm_polygons(col = "sp_lag_poblacion_2022", palette="PuOr", style="quantile", n=5, title="Densidad Poblacional") +
tm_layout(main.title= 'Clusters de Población', title.position = c('right', 'top'), legend.position= c("left", "bottom"), title.size = 1)
## tm_polygons: Deprecated tmap v3 code detected. Code translated to v4
## Warning: The 'main.title' argument of 'tm_layout()' is deprecated as of tmap
## 4.0. Please use 'tm_title()' instead.
newpob_lag