DÉFICIT HABITACIONAL

El déficit habitacional en Argentina

Los datos se obtuvieron a partir de las encuestas armonizadas de SCL DATA.

En el año 2015 en Argentina, la mayoría de los hogares habitaba en viviendas sin déficit. Sin embargo, casi 1 de cada 4 hogares residía en una vivienda con déficit cualitativo, mientras que menos de 1 hogar cada 10 vivía en un vivienda sin posibilidades de mejora.
¿Hay variabilidad en las diferentes áreas regiones relevadas por la encuesta de hogares?

Corrientes presenta el mayor nivel de déficit cuantitativo, mientras que la provincia de Buenos Aires es la region con mayor déficit habitacional.

¿Cómo varió la situación habitacional en Argentina en los últimos 6 años?

Los valores se mantienen relativamente constantes a través del tiempo.

A fin de analizar la variabilidad particular, se considera las diferencias año a año.

Este gráfico muestra como varió el déficit habitacional con respecto al año anterior en puntos porcentuales.

Se podría analizar también en relación a la variación en relación a la cantidad neta de hogares.


¿Que ocurre en America Latina?


Se observa en el mapa para el año 2015 que hay varios países con déficit cualitativo y déficit cuantitativo alto como por ejemplo: Guatemala, Honduras y Bolivia. Países como Uruguay y Costa Rica tienen déficit cualitativo medio y una baja proporción de hogares con déficit cuantitativo.

library(tidyverse)
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.3     v purrr   0.3.4
## v tibble  3.1.2     v dplyr   1.0.6
## v tidyr   1.1.3     v stringr 1.4.0
## v readr   1.4.0     v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(haven) # Import .dta files
library(scales) # Customize graphic scales
## 
## Attaching package: 'scales'
## The following object is masked from 'package:purrr':
## 
##     discard
## The following object is masked from 'package:readr':
## 
##     col_factor
library(sf) # Simple features for R
## Linking to GEOS 3.9.0, GDAL 3.2.1, PROJ 7.2.1
library(cowplot) # Place graphs at particular locations
## Warning: package 'cowplot' was built under R version 4.1.1
options(scipen = 20)

ANEXO 1: Preprocesamiento de datos

Carga de datos

data_arg <- read_dta("harmonized_surveys/ARG_2015s1_BID.dta")
data_bol <- read_dta("harmonized_surveys/BOL_2015m11_BID.dta")
data_bra <- read_dta("harmonized_surveys/BRA_2015m9_BID.dta")
data_pry <- read_dta("harmonized_surveys/PRY_2015m10_m12_BID.dta")

Definición de función para que tome las variables de interés

select_variables <- function(x) {
  nombre_variables <- readxl::read_xlsx("variables_indicador.xlsx")
  nombre_variables_list <- nombre_variables$nombre
  
  loadError <- FALSE
  
  z <- try({ x[ , nombre_variables_list, drop=FALSE] })
  
  loadError <- (is(z, 'try-error')|is(z,'error'))
  
  if(loadError == FALSE){
    
    dataframe <- x[ , nombre_variables_list, drop=FALSE]
    dataframe <- unique(dataframe) # mantener hogares con ID unico para no computar más de 1 vez el hogar
    dataframe <- filter(dataframe, !is.na(factor_ch))
    
}
  
  else {
    stop('The dataframe is not a harmonized survey') }
  
  return(dataframe)
} 
data_arg_clean <- select_variables(data_arg) 

Definición de función que calcule Calidad de Materiales (por lo menos 2 materiales deben evaluarse)

calidad_materiales <- function(x) {
  nuevo_dataset <- x %>% 
    mutate(cm = case_when(
      is.na(piso_ch) & is.na(pared_ch)  ~ NA_real_, 
      is.na(piso_ch) & is.na(techo_ch)  ~ NA_real_, 
      is.na(techo_ch) & is.na(pared_ch) ~ NA_real_, 
      
      piso_ch == 1 & pared_ch == 1 & techo_ch == 1 ~ 2, 
      piso_ch == 1 & pared_ch == 1 & is.na(techo_ch) ~ 2, 
      piso_ch == 1 & is.na(pared_ch) & techo_ch == 1 ~ 2, 
      is.na(piso_ch) & pared_ch == 1 & techo_ch == 1 ~ 2,
      
      pared_ch %in% c(0,2) ~ 0, 
      is.na(pared_ch) & piso_ch %in% c(0, 2) & techo_ch %in% c(0, 2) ~ 0,
      
      TRUE ~ 1
    
  ))
    return(nuevo_dataset)
  
}
data_arg_clean <- calidad_materiales(data_arg_clean)
table(data_arg_clean$cm)
## 
##     0     1     2 
##    27   600 36991

Definición de función que calcule la disponibilidad de agua

disponibilidad_de_agua <- function(x) {
  nuevo_dataset <- x %>% 
    mutate(ag = case_when(
      is.na(aguamejorada_ch) ~ NA_real_, 
      
      #es urbano 
      zona_c == 1 & aguamejorada_ch == 1 & aguared_ch == 1 & aguadist_ch == 1 ~ 1, 
      zona_c == 1 & aguamejorada_ch == 1 & is.na(aguared_ch) & aguadist_ch == 1 ~ 1, 
      zona_c == 1 & aguamejorada_ch == 1 & aguared_ch == 1 & is.na(aguadist_ch) ~ 1,
      zona_c == 1 & aguamejorada_ch == 1 & is.na(aguared_ch) & is.na(aguadist_ch) ~ 1,
      
      # es rural 
      zona_c == 0 & aguamejorada_ch == 1 ~ 1, 
      
      is.na(zona_c) & aguamejorada_ch == 1 ~ 1, 
      
      
      TRUE ~ 0
    
  ))
    return(nuevo_dataset)
  
}
data_arg_clean <- disponibilidad_de_agua(data_arg_clean)
table(data_arg_clean$ag)
## 
##     0     1 
##  2594 35024

Definición de función que calcule el acceso a electricidad

electricidad <- function(x) {
  nuevo_dataset <- x %>% 
    mutate(el = case_when(
      is.na(luz_ch) ~ NA_real_, 
      
      luz_ch == 1 ~ 1, 
      
      TRUE ~ 0
    
  ))
    return(nuevo_dataset)
  
}
data_arg_clean <- electricidad(data_arg_clean)
table(data_arg_clean$el)
## < table of extent 0 >
head(data_arg_clean$luz_ch)
## [1] NA NA NA NA NA NA

Definición de función que calcule el acceso a saneamiento (cloacal)

saneamiento <- function(x) {
  nuevo_dataset <- x %>% 
    mutate(cl = case_when(
      #es urbano 
      zona_c == 1 & is.na(des1_ch) ~ NA_real_, 
      zona_c == 1 & des1_ch == 1 ~ 1, 
      
      # es rural 
      zona_c == 0 & des2_ch %in% c(1,2) ~ 1, 
      zona_c == 0 & is.na(des2_ch) & des1_ch == 1 ~ 1, # es rural pero no hay datos de des2_ch 
      
      #area desconocida
      is.na(zona_c) & (des1_ch == 1  | des2_ch == 2) ~ 1, 
      
      is.na(des1_ch) ~ NA_real_, 
      is.na(des2_ch) ~ NA_real_, 
      
      TRUE ~ 0
    
  ))
    return(nuevo_dataset)
  
}
data_arg_clean <- saneamiento(data_arg_clean)
table(data_arg_clean$cl)
## 
##     0     1 
##  2597 34914

Definición de función que calcule el hacinamiento

hacinamiento <- function(x) {
  nuevo_dataset <- x %>% 
    mutate(ratio_pers_dorm = ifelse(is.na(nmiembros_ch) | is.na(dorm_ch), NA, nmiembros_ch/dorm_ch), 
           
           ha = case_when(
             ratio_pers_dorm >= 4  ~ 2, 
             ratio_pers_dorm > 2 ~ 1, 
             ratio_pers_dorm <= 2 ~ 0, 
             is.na(ratio_pers_dorm) ~ NA_real_
             )
           )
  
    return(nuevo_dataset)
  
}
data_arg_clean <- hacinamiento(data_arg_clean)
table(data_arg_clean$ha)
## 
##     0     1     2 
## 29727  4679  1630

Definición de función que calcule el tipo de vivienda

tipo_vivienda <- function(x) {
  nuevo_dataset <- x %>% 
    mutate(tv = case_when(
      is.na(vivi2_ch) ~ NA_real_, 
      vivi2_ch == 1 ~ 1, 
      vivi2_ch == 0 ~ 0
    )
      
           )
  
    return(nuevo_dataset)
  
}
data_arg_clean <- tipo_vivienda(data_arg_clean)
table(data_arg_clean$tv)
## 
##     0     1 
##   219 37399

Definición de función que calcule la clase de hogar

clase_hogar <- function(x) {
  nuevo_dataset <- x %>% 
    mutate(ch = case_when(
      is.na(clasehog_ch) ~ NA_real_, 
      clasehog_ch %in% c(1,2) ~ 1, 
      clasehog_ch %in% c(3,4,5) ~ 0
    )
      
           )
  
    return(nuevo_dataset)
  
}
data_arg_clean <- clase_hogar(data_arg_clean)
table(data_arg_clean$ch)
## 
##     0     1 
##  7204 30414

Definición de función que calcule la disponibilidad de baño exclusivo

disponibilidad_de_bano <- function(x) {
  nuevo_dataset <- x %>% 
    mutate( db = case_when(
      is.na(banoex_ch) ~ NA_real_, 
      banoex_ch == 1 ~ 1, 
      banoex_ch == 0 ~ 0
    )
      
           )
  
    return(nuevo_dataset)
  
}
data_arg_clean <- disponibilidad_de_bano(data_arg_clean)
table(data_arg_clean$db)
## 
##     0     1 
##   974 36600

Ahora con las funciones intermedias, se arma el indicador de déficit cualitativo y cuantitativo

deficit_vivienda <- function(x) {
  nuevo_dataset <- x %>% 
    mutate(deficit = case_when(
      cm == 0  ~ "Cuantitativo", 
      ha == 2  ~ "Cuantitativo", 
      tv == 0 ~ "Cuantitativo",
      ch == 0  ~ "Cuantitativo", # con CLASE DE HOGAR 
      db == 0 ~ "Cuantitativo",
      cm == 1  ~ "Cualitativo", 
      ag == 0 ~ "Cualitativo",
      el == 0 ~ "Cualitativo",
      cl == 0 ~ "Cualitativo",
      ha == 1~ "Cualitativo",
      TRUE ~ "Sin déficit"
    )
      
           )
  
    return(nuevo_dataset)
  
}
data_arg_clean <- deficit_vivienda(data_arg_clean)
table(data_arg_clean$deficit)
## 
##  Cualitativo Cuantitativo  Sin déficit 
##         5444         9143        23031

Representación con expansor

representacion_deficit <- function(x) {
  nuevo_dataset <- x %>%
    group_by(deficit) %>%
    summarise(cantidad = sum(factor_ch)) %>%
    ungroup() %>%
    mutate(deficit = factor(deficit, levels = c("Sin déficit", "Cualitativo", "Cuantitativo")))
  
  return(nuevo_dataset)
  
}
representacion_deficit(data_arg_clean)
## # A tibble: 3 x 2
##   deficit      cantidad
##   <fct>           <dbl>
## 1 Cualitativo   1553156
## 2 Cuantitativo  1972347
## 3 Sin déficit   4881588

Se arma el indicador de déficit cualitativo y cuantitativo (sin la variable clase de hogar)

deficit_vivienda2 <- function(x) {
  nuevo_dataset <- x %>% 
    mutate(deficit2 = case_when(
      cm == 0  ~ "Cuantitativo", 
      ha == 2  ~ "Cuantitativo", 
      tv == 0 ~ "Cuantitativo",
      # sin clase de hogar
      db == 0 ~ "Cuantitativo",
      cm == 1  ~ "Cualitativo", 
      ag == 0 ~ "Cualitativo",
      el == 0 ~ "Cualitativo",
      cl == 0 ~ "Cualitativo",
      ha == 1~ "Cualitativo",
      is.na(cm) & is.na(ha) & is.na(tv) & is.na(db) & is.na(ag) & is.na(el) & is.na(cl) ~ "Sin datos", 
      TRUE ~ "Sin déficit"
    )
      
           )
  
    return(nuevo_dataset)
  
}
data_arg_clean <- deficit_vivienda2(data_arg_clean)
table(data_arg_clean$deficit2)
## 
##  Cualitativo Cuantitativo  Sin déficit 
##         7558         2538        27522

Representación con expansor

representacion_deficit2 <- function(x) {
  nuevo_dataset <- x %>%
    group_by(pais_c, deficit2) %>%
    summarise(cantidad = sum(factor_ch)) %>%
    ungroup() %>%
    mutate(deficit2 = factor(deficit2, levels = c("Sin déficit", "Cualitativo", "Cuantitativo")))
  
  return(nuevo_dataset)
  
}
comparativa <- representacion_deficit(data_arg_clean) %>%
              rename(cantidad1 = cantidad) %>%
  left_join(representacion_deficit2(data_arg_clean) %>% 
              select(-pais_c) %>%
              rename(cantidad2 = cantidad), by = c("deficit" = "deficit2"))
## `summarise()` has grouped output by 'pais_c'. You can override using the `.groups` argument.
comparativa
## # A tibble: 3 x 3
##   deficit      cantidad1 cantidad2
##   <fct>            <dbl>     <dbl>
## 1 Cualitativo    1553156   2080093
## 2 Cuantitativo   1972347    596990
## 3 Sin déficit    4881588   5730008

Se toma la segunda variante de déficit (parece más razonable para argentina) y se construye una función que tome cualquier dataset como input, y genere el indicador de déficit habitacional.


indicador_deficit <- function(y) {
   
  nuevo_dataset <- y %>%
    select_variables() %>%
    calidad_materiales() %>%
    disponibilidad_de_agua() %>%
    electricidad() %>%
    saneamiento() %>%
    hacinamiento() %>%
    tipo_vivienda() %>%
    disponibilidad_de_bano() %>%
    deficit_vivienda2() %>%
    representacion_deficit2() 
  
  return(nuevo_dataset)
  
  
  
}
indicador_deficit(data_arg)
## `summarise()` has grouped output by 'pais_c'. You can override using the `.groups` argument.
## # A tibble: 3 x 3
##   pais_c deficit2     cantidad
##   <chr>  <fct>           <dbl>
## 1 ARG    Cualitativo   2080093
## 2 ARG    Cuantitativo   596990
## 3 ARG    Sin déficit   5730008

Para simplificar el trabajo con las distintas bases de datos, se construye la función iadbclean() que preprocesa una Harmonized Survey: filtra las variables que serán utilizadas por los indicadores y los gráficos, genera las nuevas variables necesarias, y estandariza el déficit

iadb_clean <- function(data) {
  
  # funcion de correccion de los caracteres especiales de las regiones
  correccion.encoding <- function( x ) {
  correccion <- c("ó" = "ó", "í" = "í", "á" = "á", "ã" = "õ", "ô" = "ô", "ñ" = "ñ", "é" = "é", "’" = "'", "ú" = "ú")
  x <- str_replace_all(x, correccion)
  
  return(x)
}

  
  nuevo_dataset <- data %>%
    select_variables() %>%
    mutate(region_c = correccion.encoding(as.character(as_factor(region_c)))) %>%
    calidad_materiales() %>%
    disponibilidad_de_agua() %>%
    electricidad() %>%
    saneamiento() %>%
    hacinamiento() %>%
    tipo_vivienda() %>%
    disponibilidad_de_bano() %>%
    deficit_vivienda2() 
  return(nuevo_dataset)
}

Antes de continuar, se optimiza la función para que pueda generar un indicador de déficit según país o región de encuesta. Por ejemplo para la EPH argentina, la región de encuesta es “Área Metropolitana”. Para eso, la función representacion_deficit2() se construye directamente dentro de la función que calcula el déficit. Se incorpora también el año de la encuesta.

indicador_deficit <- function(data, escala = "pais") {
  
  if (escala == "pais") {
    nuevo_dataset <- data %>%
      iadb_clean() %>%
      group_by(pais_c, deficit2, anio_c) %>%
      summarise(cantidad = sum(factor_ch)) %>%
      ungroup() 
    
    }
  
  else if (escala == "region"){
    nuevo_dataset <- data %>%
      iadb_clean() %>%
      group_by(pais_c, region_c, deficit2, anio_c) %>%
      summarise(cantidad = sum(factor_ch)) %>%
      ungroup() 
    
    }
  
  else {
    stop('Missing arguments')
  }  
    
  
  return(nuevo_dataset)
  
}

Ejemplos

Argentina

indicador_deficit(data = data_arg)
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.
## # A tibble: 3 x 4
##   pais_c deficit2     anio_c cantidad
##   <chr>  <chr>         <dbl>    <dbl>
## 1 ARG    Cualitativo    2015  2080093
## 2 ARG    Cuantitativo   2015   596990
## 3 ARG    Sin déficit    2015  5730008

A escala región:

data_arg %>% 
  indicador_deficit(escala = "region") %>%
  spread(key = deficit2, value = cantidad)
## `summarise()` has grouped output by 'pais_c', 'region_c', 'deficit2'. You can override using the `.groups` argument.
## # A tibble: 24 x 6
##    pais_c region_c               anio_c Cualitativo Cuantitativo `Sin déficit`
##    <chr>  <chr>                   <dbl>       <dbl>        <dbl>         <dbl>
##  1 ARG    Buenos Aires             2015     1363956       297223       2203873
##  2 ARG    Catamarca                2015       10743         4686         43934
##  3 ARG    Chaco                    2015       17592         9233         91110
##  4 ARG    Chubut                   2015       16561         9089         90480
##  5 ARG    Ciudad de Buenos Aires   2015       89284        54948       1022975
##  6 ARG    Córdoba                  2015       86940        35926        429137
##  7 ARG    Corrientes               2015       15927        15238         82552
##  8 ARG    Entre Ríos               2015       25286        11398        107230
##  9 ARG    Formosa                  2015       14488         7216         47287
## 10 ARG    Jujuy                    2015       12872         6989         68007
## # ... with 14 more rows

Bolivia

indicador_deficit(data_bol)
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.
## # A tibble: 3 x 4
##   pais_c deficit2     anio_c cantidad
##   <chr>  <chr>         <dbl>    <dbl>
## 1 BOL    Cualitativo    2015   685867
## 2 BOL    Cuantitativo   2015  1570323
## 3 BOL    Sin déficit    2015   756251

A escala región:

data_bol %>% 
  indicador_deficit(escala = "region") %>%
  spread(key = deficit2, value = cantidad)
## `summarise()` has grouped output by 'pais_c', 'region_c', 'deficit2'. You can override using the `.groups` argument.
## # A tibble: 9 x 6
##   pais_c region_c   anio_c Cualitativo Cuantitativo `Sin déficit`
##   <chr>  <chr>       <dbl>       <dbl>        <dbl>         <dbl>
## 1 BOL    Beni         2015       39163        64290          8221
## 2 BOL    Chuquisaca   2015       21782        99442         45427
## 3 BOL    Cochabamba   2015      141335       242785        132639
## 4 BOL    La Paz       2015      177441       403577        228014
## 5 BOL    Oruro        2015       32979       103046         21906
## 6 BOL    Pando        2015       17082        14399          1995
## 7 BOL    Potosí       2015       32309       192022         27922
## 8 BOL    Santa Cruz   2015      187169       379564        246457
## 9 BOL    Tarija       2015       36607        71198         43670

Brasil

indicador_deficit(data_bra)
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.
## # A tibble: 3 x 4
##   pais_c deficit2     anio_c cantidad
##   <chr>  <chr>         <dbl>    <dbl>
## 1 BRA    Cualitativo    2015 15701619
## 2 BRA    Cuantitativo   2015  2472922
## 3 BRA    Sin déficit    2015 53789858

Paraguay a nivel region

data_pry %>% 
  indicador_deficit(escala = "region") 
## `summarise()` has grouped output by 'pais_c', 'region_c', 'deficit2'. You can override using the `.groups` argument.
## # A tibble: 21 x 5
##    pais_c region_c    deficit2     anio_c cantidad
##    <chr>  <chr>       <chr>         <dbl>    <dbl>
##  1 PRY    Alto Paraná Cualitativo    2015   126325
##  2 PRY    Alto Paraná Cuantitativo   2015    21969
##  3 PRY    Alto Paraná Sin déficit    2015    70447
##  4 PRY    Asunción    Cualitativo    2015    83820
##  5 PRY    Asunción    Cuantitativo   2015    26300
##  6 PRY    Asunción    Sin déficit    2015    29208
##  7 PRY    Caaguazú    Cualitativo    2015    48638
##  8 PRY    Caaguazú    Cuantitativo   2015     8049
##  9 PRY    Caaguazú    Sin déficit    2015    73370
## 10 PRY    Central     Cualitativo    2015   354750
## # ... with 11 more rows

ANEXO 2: Visualizaciones

Descripción general de déficit

plot_deficit <- function(data) {
  
  x <- indicador_deficit(data)  %>%
    mutate(ratio = round(cantidad * 100 /sum(cantidad), digits = 2),
           deficit2 = factor(deficit2, levels = c("Sin déficit", "Cualitativo", "Cuantitativo")))
  
  pais <- x %>%
    select(pais_c) %>%
    unique() %>%
    .$pais_c
  
  anio <- min(x$anio_c)


  ggplot(data = x ) +
    geom_bar(aes(x = deficit2, weight = cantidad, fill = deficit2))  + 
    geom_text(aes(x = deficit2, y = cantidad, label = paste0(ratio, "%")), vjust = -0.2, size = 4.2,fontface = "bold") + 
    geom_text(aes(x = deficit2, y = cantidad, label = paste0(scales::comma(cantidad), " hogares")),
              vjust = 1.5, size = 3.2) + 
    labs(title = paste0("Déficit habitacional en ", pais, " (", anio, ")"), 
        caption = "A partir de Harmonized Survey - IDB") + 
    scale_fill_manual(values = c("#7fbf7b", "#5AC8C8", "#BE64AC")) + 
    scale_y_continuous(labels = comma) +
    theme_minimal() + 
    theme(legend.position = "none", 
          axis.title = element_blank(), 
          legend.title = element_blank())
  
  
} 
plot_deficit(data_arg)
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.

Bolivia

plot_deficit(data_bol)
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.

Paraguay

plot_deficit(data_pry)
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.

Brasil

plot_deficit(data_bra)
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.

Gráficos en función de las áreas de análisis de la encuesta

plot_deficit_region <- function(data, tipo = "relativo") { # ver si se incorpora parámetro de año
  
  x <- indicador_deficit(data, escala = "region" )  %>%
    group_by(region_c) %>%
    mutate(ratio = round(cantidad * 100 /sum(cantidad), digits = 2)) %>%
    ungroup() 
  
  pais <- x %>%
    select(pais_c) %>%
    unique() %>%
    .$pais_c
  
  anio <- x %>% 
    select(anio_c) %>%
    unique() %>%
    .$anio_c
  

  if (tipo == "relativo") {
    
    region_orden_rel <- x %>%
      select(region_c, deficit2, ratio) %>%
      spread(key = deficit2, value = ratio) %>%
      arrange(Cuantitativo) %>%
      .$region_c
    
    x$region_c <- factor(x$region_c, levels = region_orden_rel)

    ggplot(data = x, aes(x = region_c, y = ratio,
                         fill = factor(deficit2, levels = c("Sin déficit", "Cualitativo", "Cuantitativo"))) ) +
      geom_bar(stat = "identity")  + 
      geom_text(aes(label = paste0(ratio, "%")), position=position_stack(vjust=0.5), size = 3) + 
      scale_fill_manual(values = c("#7fbf7b", "#5AC8C8", "#BE64AC")) + 
      labs(title = paste0("Déficit habitacional en ", pais, " (", anio, ")"), 
           subtitle = "Valores Relativos", 
           fill = "Déficit", 
           caption = "A partir de Harmonized Survey - IDB")+ 
      scale_y_continuous(labels = comma) +
      guides(fill = guide_legend(title.position = "top", nrow = 1)) + 
      coord_flip() + 
      theme_minimal() + 
      theme(legend.position = "bottom", 
            axis.title = element_blank())
  }
  
  else if (tipo == "absoluto") {
    
    region_orden_abs <- x %>%
      select(region_c, deficit2, cantidad) %>%
      spread(key = deficit2, value = cantidad) %>%
      arrange(Cuantitativo) %>%
      .$region_c
      
    x$region_c <- factor(x$region_c, levels = region_orden_abs)
    
   ggplot(data = x, 
          aes(x = region_c, y = cantidad,
              fill = factor(deficit2, levels = c("Sin déficit", "Cualitativo", "Cuantitativo"))
              ) 
          ) +
      geom_bar(stat = "identity")  + 
      labs(title = paste0("Déficit habitacional en ", pais, " (", anio, ")"), 
           subtitle = "Valores Absolutos", 
           fill = "Déficit", 
           caption = "A partir de Harmonized Survey - IDB") + 
      scale_fill_manual(values = c("#7fbf7b", "#BE64AC", "#5AC8C8")) + 
      scale_y_continuous(labels = comma) +
      guides(fill = guide_legend(title.position =  "top", nrow = 1)) + 
      coord_flip() + 
      theme_minimal() + 
      theme(legend.position = "bottom", 
            axis.title = element_blank())
  }
  
  else {
    stop('Missing arguments')
  }  
  
}
plot_deficit_region(data_arg)
## `summarise()` has grouped output by 'pais_c', 'region_c', 'deficit2'. You can override using the `.groups` argument.

En valores relativos están ordenados por áreas con mayor déficit

plot_deficit_region(data_arg, tipo ="absoluto")
## `summarise()` has grouped output by 'pais_c', 'region_c', 'deficit2'. You can override using the `.groups` argument.

Otros países

plot_deficit_region(data_bol)
## `summarise()` has grouped output by 'pais_c', 'region_c', 'deficit2'. You can override using the `.groups` argument.

Los valores de Bolivia son muy extraños. Si se quita la disponibilidad de baño, entonces los valores de déficit cuantitativo se reducen, pero aumenta considerablemente el déficit cualitativo.

plot_deficit_region(data_pry)
## `summarise()` has grouped output by 'pais_c', 'region_c', 'deficit2'. You can override using the `.groups` argument.

¿Que significa que una región es NA? Está en la data original…

Evolución temporal del déficit

Se toma Argentina como caso de estudio.

data_arg2015 <- data_arg
data_arg2014 <- read_dta("harmonized_surveys/ARG_2014s2_BID.dta")
data_arg2016<- read_dta("harmonized_surveys/ARG_2016s2_BID.dta")
data_arg2017 <- read_dta("harmonized_surveys/ARG_2017s1_BID.dta")
data_arg2018 <- read_dta("harmonized_surveys/ARG_2018s2_BID.dta")
data_arg2019 <- read_dta("harmonized_surveys/ARG_2019t2_BID.dta")
data_arg2020 <- read_dta("harmonized_surveys/ARG_2020t1_t3_BID.dta")

La cantidad de variables por año varía:

lista.dataARG <- list(data_arg2014, data_arg2015, data_arg2016, data_arg2016, data_arg2017, data_arg2017, data_arg2018, data_arg2019, data_arg2020)
lapply(lista.dataARG, dim)
## [[1]]
## [1] 122477    412
## 
## [[2]]
## [1] 120173    419
## 
## [[3]]
## [1] 117704    422
## 
## [[4]]
## [1] 117704    422
## 
## [[5]]
## [1] 118430    422
## 
## [[6]]
## [1] 118430    422
## 
## [[7]]
## [1] 114297    425
## 
## [[8]]
## [1] 59258   417
## 
## [[9]]
## [1] 130460    417
dataARG_temp <- map(lista.dataARG, select_variables) %>% #se aplica a todos los df la funcion de variables
  bind_rows() # se unen todas las rows

Ahora se grafica

plot_deficit_ev <-  function(data) {
  
  x <- indicador_deficit(data)  %>%
    group_by(anio_c) %>%
    mutate(ratio = round(cantidad * 100 /sum(cantidad), digits = 2)) %>%
    ungroup()
  
  pais <- x %>%
    select(pais_c) %>%
    unique() %>%
    .$pais_c


  ggplot(data = x,
         aes(x= anio_c, y = ratio, color = factor(deficit2, levels = c("Sin déficit", "Cualitativo", "Cuantitativo")))) +
    geom_line(aes( group = deficit2))  +
    geom_point(size = 3) +
    geom_text(aes(label = paste0(ratio, "%")), color = "black", vjust = -0.4, size = 4) + 
    labs(title = paste0("Déficit habitacional en ", pais), 
        caption = "A partir de Harmonized Survey - IDB", 
        color = "Calidad de la vivienda") + 
    scale_color_manual(values = c("#7fbf7b", "#5AC8C8", "#BE64AC")) + 
    scale_y_continuous(labels =  scales::percent_format(scale = 1), breaks = seq(0, 100, 10), limits = c(0,100)) +
    scale_x_continuous(breaks = seq(min(x$anio_c), max(x$anio_c), 1))+
    guides(color = guide_legend(title.position = "top", nrow = 1)) + 
    theme_minimal() + 
    theme(legend.position = "bottom", 
          axis.title = element_blank(), 
          legend.title = element_blank())
  
  
} 
plot_deficit_ev(dataARG_temp)
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.

Variantes del mismo gráfico:

plot_deficit_ev2 <- function(data) { 

  anio_low <- min(data$anio_c)
  
  x <- indicador_deficit(data)  %>%
      group_by(anio_c) %>%
      mutate(ratio = round(cantidad * 100 /sum(cantidad), digits = 2)) %>%
      ungroup() %>% 
      arrange(deficit2, anio_c) %>%
      filter(deficit2 != "Sin déficit") %>%
      mutate(anio_anterior = ifelse(anio_c == anio_low, 0,  lag(ratio)), 
             variacion = ifelse(anio_c == anio_low, 0, round(ratio - anio_anterior, digits = 2 )))
  
  pais <- x %>%
    select(pais_c) %>%
    unique() %>%
    .$pais_c


  ggplot(data = x,
         aes(x= anio_c, y = variacion, color = factor(deficit2, levels = c("Cualitativo", "Cuantitativo")))) +
    geom_line(aes( group = deficit2), size = 1.2)  +
    geom_point(size = 3) +
    geom_text(aes(label = variacion), color = "black", hjust = -0.25, size = 4) + 
    labs(title = paste0("Déficit habitacional en ", pais),
         subtitle = "Variación en puntos porcentuales en relación al año anterior",
        caption = "A partir de Harmonized Survey - IDB", 
        color = "% de hogares según déficit") + 
    scale_color_manual(values = c("#5AC8C8", "#BE64AC")) + 
    scale_x_continuous(breaks = seq(min(x$anio_c), max(x$anio_c), 1))+
    guides(color = guide_legend(title.position = "top", nrow = 1)) + 
    theme_minimal() + 
    theme(legend.position = "bottom", 
          axis.title = element_blank())
  
}
plot_deficit_ev2(dataARG_temp) 
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.

Otra versión

plot_deficit_ev3 <- function(data) { 

  anio_low <- min(data$anio_c)
  
  x <- indicador_deficit(data)  %>%
    group_by(anio_c) %>%
    mutate(ratio = round(cantidad * 100 /sum(cantidad), digits = 2)) %>%
    ungroup() %>% 
    arrange(deficit2, anio_c) %>%
    filter(deficit2 != "Sin déficit") %>%
    mutate(variacion = ifelse(anio_c == anio_low, 0, round((cantidad - lag(cantidad))*100/lag(cantidad), digits = 2 )))
  
  pais <- x %>%
    select(pais_c) %>%
    unique() %>%
    .$pais_c


  ggplot(data = x,
         aes(x= anio_c, y = variacion, color = factor(deficit2, levels = c("Cualitativo", "Cuantitativo")))) +
    geom_line(aes( group = deficit2), size = 1.2)  +
    geom_point(size = 3) +
    geom_text(aes(label = paste0(variacion, "%")), color = "black", vjust = -0.3, size = 4) + 
    labs(title = paste0("Déficit habitacional en ", pais),
         subtitle = "Variación según cantidad absoluta de hogares",
        caption = "A partir de Harmonized Survey - IDB", 
        color = "Calidad de la vivienda") + 
    scale_color_manual(values = c("#5AC8C8", "#BE64AC")) + 
    scale_x_continuous(breaks = seq(min(x$anio_c), max(x$anio_c), 1))+
    guides(color = guide_legend(title.position = "top", nrow = 1)) + 
    theme_minimal() + 
    theme(legend.position = "bottom", 
          axis.title = element_blank(), 
          legend.title = element_blank())
  
}
plot_deficit_ev3(dataARG_temp)
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.

Ecuador

dataBOL <-  map(list(read_dta("harmonized_surveys/BOL_2013m11_BID.dta"),
                     read_dta("harmonized_surveys/BOL_2014m11_BID.dta"),
                     read_dta("harmonized_surveys/BOL_2015m11_BID.dta"), 
                     read_dta("harmonized_surveys/BOL_2016m11_BID.dta"),
                     read_dta("harmonized_surveys/BOL_2017m11_BID.dta"),
                     read_dta("harmonized_surveys/BOL_2018m11_BID.dta")),
                select_variables) %>% 
  bind_rows() 

Alternativa 1

plot_deficit_ev(dataBOL)
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.

Alternativa 2

plot_deficit_ev2(dataBOL)
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.

Alternativa 3

plot_deficit_ev3(dataBOL)
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.


Ubicación espacial

Creo que la parte espacial no debería ser parte del paquete

lac_geo <- rnaturalearth::ne_countries(scale = "medium", returnclass = "sf") %>%
  filter(region_wb == "Latin America & Caribbean") %>%
  select(iso_a3, name) %>%
  st_transform(crs = 4326)
ggplot() +
  geom_sf(data = lac_geo)

Se calcula los indicadores de situación habitacional para los 4 países cargados en 2015:

latam2015 <- read.csv("harmonized_surveys/latam2015-hs.csv")
latam2015_indicadores <- indicador_deficit(latam2015) %>%
  group_by(pais_c) %>%
  mutate(ratio = round(cantidad /sum(cantidad), digits = 2)) %>%
  ungroup()
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.

Se construye un indicador de niveles de déficit:
* Cualitativo:
- menos de 10%: bajo
- entre 10% y 20%: medio
- más de 20%: alto

  • Cuantitativo:
  • menos de 5%: bajo
  • entre 5% y 10%: medio
  • más de 10%: alto
cuali <- c(1, )
niveles_deficit <- 
## Error: <text>:3:0: unexpected end of input
## 1: cuali <- c(1, )
## 2: niveles_deficit <- 
##   ^
latam2015_indicadores2 <- latam2015_indicadores %>%
  filter(deficit2 %in% c("Cualitativo", "Cuantitativo")) %>%
  select(-cantidad) %>%
  spread(key = deficit2, value = ratio) %>%
  mutate(
    Cuali = case_when( # eje x
      Cualitativo <= 0.1 ~ "1", 
      Cualitativo <= 0.2 ~ "2", 
      Cualitativo > 0.2 ~ "3" 
      ), 
    Cuanti = case_when( # eje y
      Cuantitativo <= 0.05 ~ "1", 
      Cuantitativo <= 0.1 ~ "2", 
      Cuantitativo > 0.1 ~ "3" 
    ), 
    bi_class = paste0(Cuali, "-", Cuanti)
  )

Se realiza la unión de las geometrías, con el cálculo de indicadores.

lac_geo <- lac_geo %>%
  left_join(latam2015_indicadores2, by = c("iso_a3" = "pais_c"))
map <- ggplot() +
  geom_sf(data = lac_geo, aes(fill = bi_class), color = "white",  show.legend = FALSE) +
  geom_sf_text(data = lac_geo  %>%
                     filter(!is.na(bi_class)), 
               aes(label = iso_a3), size = 2) + 
  bi_scale_fill(pal = "DkBlue", dim = 3, na.value = "grey40") +
  labs(
    title = "Comparación de la situación habitacional",
    subtitle = "Año 2015 para países con Harmonized Survey"
  )  + 
  theme_void() + 
  theme(plot.title = element_text(hjust = 0.5), 
        plot.subtitle = element_text(hjust = 0.5))
## Error in bi_scale_fill(pal = "DkBlue", dim = 3, na.value = "grey40"): no se pudo encontrar la función "bi_scale_fill"
legend <- bi_legend(pal = "DkBlue",
                    dim = 3,
                    xlab = "Mayor déficit cualitativo ",
                    ylab = "Mayor déficit cuantitativo",
                    size = 5)
## Error in bi_legend(pal = "DkBlue", dim = 3, xlab = "Mayor déficit cualitativo ", : no se pudo encontrar la función "bi_legend"
finalPlot <- ggdraw() +
  draw_plot(map,x = 0, y= 0, width= 1, height =  1) +
  draw_plot(legend, x = 0.1, y = 0.05, width = 0.25,  height = 0.25)
## Warning: Package `gridGraphics` is required to handle base-R plots. Substituting
## empty plot.

## Warning: Package `gridGraphics` is required to handle base-R plots. Substituting
## empty plot.
finalPlot

ggmap::ggmap(lac_base)+
  geom_sf(data = lac_geo %>%
            filter(!is.na(ratio)),
          aes(fill = ratio), inherit.aes = FALSE, alpha = 0.9) + 
  facet_wrap(~ deficit2) + 
  guides(fill = guide_colorbar(barheight = 1, barwidth = 30, title.position = "top")) +
  scale_fill_distiller(palette = "GnBu", direction = 1, labels = scales::percent_format()) + 
  labs(title = "Comparación de la situación habitacional", 
       subtitle = "Año 2015", 
       fill = "% de Hogares sobre el total") + 
  theme_void() + 
  theme(legend.position = "bottom")
## Error in ggmap::ggmap(lac_base): objeto 'lac_base' no encontrado


Detalle sobre qué déficit tienen las viviendas deficitarias

Las viviendas pueden ser deficitarias por múltiples causas. A continuación, se busca discriminar las variables que hacen que una vivienda sea considerada como en déficit cualitativo o cuantivativo.

categorias_de_deficit <- function(x){
  x <- x %>% 
    mutate(
      `Calidad de los materiales` = case_when(
        cm == 0 ~ "Déficit cuantitativo", 
        cm == 1 ~ "Déficit cualitativo", 
        is.na(cm) ~ "Sin datos", 
        TRUE ~ "Sin déficit"
        ), 
      
      `Disponibilidad de agua` = case_when(
        ag == 0 ~ "Déficit cualitativo",  
        is.na(ag) ~ "Sin datos", 
        TRUE ~ "Sin déficit" 
        ), 
      
      `Provisión de electricidad` = case_when(
        el == 0 ~ "Déficit cualitativo",  
        is.na(el) ~ "Sin datos", 
        TRUE ~ "Sin déficit" 
        ), 
      
      `Alcantarillado` = case_when(
        cl == 0 ~ "Déficit cualitativo",  
        is.na(cl) ~ "Sin datos", 
        TRUE ~ "Sin déficit" 
        ), 
      
      `Hacinamiento` = case_when(
        ha == 2 ~ "Déficit cuantitativo", 
        ha == 1 ~ "Déficit cualitativo", 
        is.na(ha) ~ "Sin datos", 
        TRUE ~ "Sin déficit"
        ),
      
      `Tipo de Vivienda` = case_when(
        tv == 0 ~ "Déficit cuantitativo", 
        is.na(tv) ~ "Sin datos", 
        TRUE ~ "Sin déficit"
        ),
      
      `Baño Exclusivo` = case_when(
        db == 0 ~ "Déficit cuantitativo", 
        is.na(db) ~ "Sin datos", 
        TRUE ~ "Sin déficit"
        )
      
      ) 
  return(x)
}

tipo_de_deficit <- function(x) {
  x <- x %>% 
    categorias_de_deficit() %>%
    gather(key = "parametro", value = "estado", `Calidad de los materiales`:`Baño Exclusivo`) %>%
    group_by(pais_c, deficit2, parametro, estado ) %>%
    summarise(cantidad = sum(factor_ch, na.rm = TRUE)) %>%
    mutate(estado = factor(estado, levels = c("Sin déficit", "Déficit cualitativo", "Déficit cuantitativo", "Sin datos")),
           def_global = factor(deficit2, levels = c("Sin déficit", "Cualitativo", "Cuantitativo"))) %>%
    ungroup()
  
  return(x)
  
} 
data_arg_agrupada <- tipo_de_deficit(data_arg_clean)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'parametro'. You can override using the `.groups` argument.
data_arg_agrupada
## # A tibble: 39 x 6
##    pais_c deficit2    parametro                 estado       cantidad def_global
##    <chr>  <chr>       <chr>                     <fct>           <dbl> <fct>     
##  1 ARG    Cualitativo Alcantarillado            Déficit cua~   630187 Cualitati~
##  2 ARG    Cualitativo Alcantarillado            Sin déficit   1449906 Cualitati~
##  3 ARG    Cualitativo Baño Exclusivo            Sin datos          84 Cualitati~
##  4 ARG    Cualitativo Baño Exclusivo            Sin déficit   2080009 Cualitati~
##  5 ARG    Cualitativo Calidad de los materiales Déficit cua~    84197 Cualitati~
##  6 ARG    Cualitativo Calidad de los materiales Sin déficit   1995896 Cualitati~
##  7 ARG    Cualitativo Disponibilidad de agua    Déficit cua~   830253 Cualitati~
##  8 ARG    Cualitativo Disponibilidad de agua    Sin déficit   1249840 Cualitati~
##  9 ARG    Cualitativo Hacinamiento              Déficit cua~  1043819 Cualitati~
## 10 ARG    Cualitativo Hacinamiento              Sin datos       47853 Cualitati~
## # ... with 29 more rows
  dataset_agrupado <- data_arg %>%
    iadb_clean() %>%
    tipo_de_deficit() %>%
    group_by(def_global,  parametro) %>%
    mutate(ratio= cantidad / sum(cantidad, na.rm = TRUE)) %>%
    ungroup()
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'parametro'. You can override using the `.groups` argument.
plot_deficit_detalle <- function(data) {
  
  pais <- data %>%
    select(pais_c) %>%
    unique() %>%
    .$pais_c
  
  dataset_agrupado <- data %>%
    iadb_clean() %>%
    tipo_de_deficit() %>%
    group_by(def_global, parametro) %>%
    mutate(ratio= cantidad / sum(cantidad, na.rm = TRUE)) %>%
    ungroup()
  
  anio <- min(data$anio_c)
  
  plot <- ggplot(data = dataset_agrupado, aes(x = parametro, fill = estado, y= ratio) ) + 
    geom_bar(stat = "identity") + 
    geom_text(aes(label =paste0(round(ratio*100, digits = 0), "%")), position=position_stack(vjust=0.5), size = 3) + 
    labs(title = paste0(pais, ": Composición del défiticit de vivienda (", anio, ")"), 
       caption = "A partir de Harmonized Survey - IDB") + 
    facet_wrap(~ def_global)+ 
    scale_fill_manual(values = c("#7fbf7b", "#5AC8C8", "#BE64AC", "grey")) + 
    scale_y_continuous(breaks = seq(0, 1, 0.2), labels = paste0(seq(0, 100, 20), "%")) + 
    coord_flip() + 
    theme_minimal() + 
    theme(legend.position = "bottom", 
        axis.title = element_blank(), 
        legend.title = element_blank())
  
  return(plot)
  
}
plot_deficit_detalle(data_arg)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'parametro'. You can override using the `.groups` argument.

Veamos para otros países

Bolivia

plot_deficit_detalle(data_bol)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'parametro'. You can override using the `.groups` argument.

Brasil

plot_deficit_detalle(data_bra)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'parametro'. You can override using the `.groups` argument.

Paraguay

plot_deficit_detalle(data_pry)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'parametro'. You can override using the `.groups` argument.

Déficit de vivienda (heatmap)

ggplot(data = data_arg_agrupada) + 
  geom_tile(aes(x = estado, y = parametro, fill = cantidad)) + 
  facet_wrap(~ def_global) + 
  guides(fill=guide_colourbar(title.position = "top", barwidth  = 40, barheight = 2)) + 
  scale_fill_distiller(palette = "Spectral" , direction = 1, labels = comma) + 
  theme_minimal() + 
  theme(legend.position = "bottom", 
        axis.text.x = element_text(angle = 90, vjust = 0.5), 
        axis.title = element_blank())

tiles_deficit <- function(dataset) {
  
  pais <- dataset %>%
    select(pais_c) %>%
    unique() %>%
    .$pais_c
  
  dataset_agrupado <- dataset %>%
    iadb_clean() %>%
    tipo_de_deficit()
  
  plot <- ggplot(data = dataset_agrupado ) + 
    geom_tile(aes(x = estado, y = parametro, fill = cantidad)) + 
    facet_wrap(~ def_global) + 
    labs(title = paste0(pais, ": Hogares en déficit discriminado por indicador"), 
       caption = "A partir de Harmonized Survey - IDB", 
       fill = "Cantidad de hogares") + 
    guides(fill=guide_colourbar(title.position = "top", barwidth  = 40, barheight = 2)) + 
    scale_fill_distiller(palette = "YlGnBu" , direction = 1, labels = comma) + 
    theme_minimal() + 
    theme(legend.position = "bottom", 
        axis.text.x = element_text(angle = 90, vjust = 0.5), 
        axis.title = element_blank())
    
    
  
  return(plot)
  
}

Argentina

tiles_deficit(data_arg)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'parametro'. You can override using the `.groups` argument.

Bolivia

tiles_deficit(data_bol)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'parametro'. You can override using the `.groups` argument.

En este gráfico se puede observar que los indicadores de “baño exclusivo” y de “hacinamiento” son los que penalizan considerablemente a los hogares en Bolivia para déficit cuantitativo.

Brasil

tiles_deficit(data_bra)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'parametro'. You can override using the `.groups` argument.

Paraguay

tiles_deficit(data_pry)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'parametro'. You can override using the `.groups` argument.

Déficit de vivienda (treemap)

data_arg_acum <- data_arg_clean %>%
  categorias_de_deficit() %>%
  group_by(deficit2, `Calidad de los materiales`, `Hacinamiento`, `Tipo de Vivienda`, `Baño Exclusivo`, `Disponibilidad de agua`, `Provisión de electricidad`, `Alcantarillado`  ) %>%
  summarise(cantidad = sum(factor_ch)) %>%
  ungroup() %>% 
  mutate(grupo_acum = paste0("Materiales: ", `Calidad de los materiales`, " /  Hacinamiento: ", `Hacinamiento`,  " / Tipo: ", `Tipo de Vivienda`, " / Allegamiento: ", `Baño Exclusivo`, " /Agua: ", `Disponibilidad de agua`, " / Electricidad: ", `Provisión de electricidad`, " / Alcantarillado: ", `Alcantarillado` )) 
## `summarise()` has grouped output by 'deficit2', 'Calidad de los materiales', 'Hacinamiento', 'Tipo de Vivienda', 'Baño Exclusivo', 'Disponibilidad de agua', 'Provisión de electricidad'. You can override using the `.groups` argument.
head(data_arg_acum)
## # A tibble: 6 x 10
##   deficit2    `Calidad de los m~ Hacinamiento  `Tipo de Vivien~ `Baño Exclusivo`
##   <chr>       <chr>              <chr>         <chr>            <chr>           
## 1 Cualitativo Déficit cualitati~ Déficit cual~ Sin déficit      Sin déficit     
## 2 Cualitativo Déficit cualitati~ Déficit cual~ Sin déficit      Sin déficit     
## 3 Cualitativo Déficit cualitati~ Déficit cual~ Sin déficit      Sin déficit     
## 4 Cualitativo Déficit cualitati~ Déficit cual~ Sin déficit      Sin déficit     
## 5 Cualitativo Déficit cualitati~ Sin datos     Sin déficit      Sin déficit     
## 6 Cualitativo Déficit cualitati~ Sin datos     Sin déficit      Sin déficit     
## # ... with 5 more variables: Disponibilidad de agua <chr>,
## #   Provisión de electricidad <chr>, Alcantarillado <chr>, cantidad <dbl>,
## #   grupo_acum <chr>
library(treemap)
## Warning: package 'treemap' was built under R version 4.1.1
plot <- treemap(data_arg_acum,
            index=c("deficit2","grupo_acum"),
            vSize="cantidad",
            type="index",
            palette = "Paired",
            align.labels= list(c("center", "center"), c( "right", "top")),
            overlap.labels = 0)

Treemap 2

Voy a probar generar 3 categorías de déficit que pueden combinarse:
- Deficit de materiales (cuali y cuanti)
- Deficit de servicios (cuali) - Hacinamiento + allegamiento (cuali y cuanti)

categorias_de_deficit3 <- function(data) {
  x <- data %>% 
    categorias_de_deficit() %>%
    mutate(
    Servicios = case_when(
      `Disponibilidad de agua` == "Déficit cualitativo" | `Provisión de electricidad` == "Déficit cualitativo" | `Alcantarillado`== "Déficit cualitativo"
      ~ "Déficit cualitativo", 
      `Disponibilidad de agua` == "Sin déficit" | `Provisión de electricidad` == "Sin déficit" | `Alcantarillado`== "Sin déficit" 
      ~ "Sin déficit", 
    
      TRUE ~ "Sin datos" 
      ), 
    `Hacinamiento + Allegamiento` = case_when(
      `Hacinamiento`==  "Déficit cuantitativo" | `Tipo de Vivienda` ==  "Déficit cuantitativo"| `Baño Exclusivo`==  "Déficit cuantitativo"
      ~  "Déficit cuantitativo",
      
      `Hacinamiento`==  "Déficit cualitativo"
      ~ "Déficit cualitativo", 
      
      `Hacinamiento`==  "Sin déficit" | `Tipo de Vivienda` ==  "Sin déficit" | `Baño Exclusivo`==  "Sin déficit" 
      ~  "Sin déficit" , 
    
      TRUE ~ "Sin datos" 
    )
    
    )
  
  return(x)
}
data_arg_tipo <- data_arg_clean %>%
   categorias_de_deficit3 %>% 
  group_by(pais_c, deficit2, `Calidad de los materiales`, `Hacinamiento + Allegamiento`, Servicios ) %>%
  summarise(cantidad = sum(factor_ch)) %>%
  ungroup() %>% 
  mutate(grupo_acum = paste0("Materiales: ", `Calidad de los materiales`, " /  Hacinamiento + Allegamiento: ", `Hacinamiento + Allegamiento`, " / Servicios: ", Servicios )) 
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'Calidad de los materiales', 'Hacinamiento + Allegamiento'. You can override using the `.groups` argument.

Volvamos a probar el treemap

plot <- treemap(data_arg_tipo,
            index=c("deficit2","grupo_acum"),
            vSize="cantidad",
            type="index",
            palette = "Paired",
            align.labels= list(c("center", "center"), c( "right", "top")),
            overlap.labels = 0)

Queda más claro

Déficit de vivienda (sankey)

library(networkD3)
## Warning: package 'networkD3' was built under R version 4.1.1
data_arg_links <- rbind(
   data_arg_tipo %>%
    mutate(Cmat = paste0("CMat: ",`Calidad de los materiales`),
         HA = paste0("HA: ", `Hacinamiento + Allegamiento`), 
         Serv = paste0("Serv: ", Servicios), 
         Gen = paste0("Gen: ", deficit2)) %>%
    select(Gen, Serv, cantidad) %>%
    rename(source = Gen, 
           target = Serv), 
   
  data_arg_tipo %>%
    mutate(Cmat = paste0("CMat: ",`Calidad de los materiales`),
         HA = paste0("HA: ", `Hacinamiento + Allegamiento`), 
         Serv = paste0("Serv: ", Servicios )) %>%
    select(Serv, HA, cantidad) %>%
    rename(source = Serv, 
           target = HA), 
  
  data_arg_tipo %>%
    mutate(Cmat = paste0("CMat: ",`Calidad de los materiales`),
         HA = paste0("HA: ", `Hacinamiento + Allegamiento`), 
         Serv = paste0("Serv: ", Servicios )) %>%
    select(HA, Cmat, cantidad) %>%
    rename(source = HA, 
           target = Cmat) ) %>%
  
  group_by(source, target) %>%
  summarise(cantidad = sum(cantidad)) %>%
  ungroup() 
## `summarise()` has grouped output by 'source'. You can override using the `.groups` argument.
head(data_arg_links)
## # A tibble: 6 x 3
##   source                  target                    cantidad
##   <chr>                   <chr>                        <dbl>
## 1 Gen: Cualitativo        Serv: Déficit cualitativo  1284200
## 2 Gen: Cualitativo        Serv: Sin déficit           795893
## 3 Gen: Cuantitativo       Serv: Déficit cualitativo   233534
## 4 Gen: Cuantitativo       Serv: Sin déficit           363456
## 5 Gen: Sin déficit        Serv: Sin déficit          5730008
## 6 HA: Déficit cualitativo CMat: Déficit cualitativo    19207
nodes_arg <- data.frame(
  name=c(as.character(data_arg_links$source), 
  as.character(data_arg_links$target)) %>% unique()) %>%
  mutate(group = as.factor(case_when(
    substr(name,1,2) == "Ge" ~ "General", 
    substr(name,1,2) == "HA" ~ "Hacinamiento",
    substr(name,1,2) == "Se" ~ "Servicios",
    substr(name,1,2) == "CM" ~ "Materiales" 
  )))

data_arg_links$IDsource <- match(data_arg_links$source, nodes_arg$name)-1 
data_arg_links$IDtarget <- match(data_arg_links$target, nodes_arg$name)-1

colores <- 'd3.scaleOrdinal() .domain(["General", "Servicios","Hacinamiento", "Materiales"]) .range(["#bebada", "#fb8072", "#80b1d3", "#fdb462"])'

Grafico

sankeyNetwork(Links = data_arg_links, Nodes = nodes_arg,
              Source = "IDsource", Target = "IDtarget",
              Value = "cantidad", NodeID = "name", 
               colourScale=colores, NodeGroup="group")
## Links is a tbl_df. Converting to a plain data frame.

Función para gráfico de Sankey
(Evaluar si es una función que puede elegir Sankey / Treemap / Bar / Titles)

plot_sankey <- function(data){
  
    dataset <- data %>%
    iadb_clean() %>%
    categorias_de_deficit3 %>% 
    group_by(pais_c, deficit2, `Calidad de los materiales`, `Hacinamiento + Allegamiento`, Servicios ) %>%
    summarise(cantidad = sum(factor_ch)) %>%
    ungroup() %>% 
    mutate(Cmat = paste0("CMat: ",`Calidad de los materiales`),
           HA = paste0("HA: ", `Hacinamiento + Allegamiento`), 
           Serv = paste0("Serv: ", Servicios), 
           Gen = paste0("Gen: ", deficit2))
  
    
  dataset_link <- rbind(
    dataset %>%
      select(Gen, Serv, cantidad) %>%
      rename(source = Gen, 
               target = Serv),
      
    dataset %>%
      select(Serv, HA, cantidad) %>%
      rename(source = Serv, 
               target = HA), 
      
    dataset %>%
      select(HA, Cmat, cantidad) %>%
      rename(source = HA, 
               target = Cmat) ) %>%
    
    group_by(source, target) %>%
    summarise(cantidad = sum(cantidad)) %>%
    ungroup() 
  
  
  nodes <- data.frame(name=c(as.character(dataset_link$source), 
                             as.character(dataset_link$target)) %>% 
                        unique()) %>%
    
    mutate(group = as.factor(case_when(
      substr(name,1,2) == "Ge" ~ "General", 
      substr(name,1,2) == "HA" ~ "Hacinamiento",
      substr(name,1,2) == "Se" ~ "Servicios",
      substr(name,1,2) == "CM" ~ "Materiales" 
  )))
  
  dataset_link$IDsource <- match(dataset_link$source, nodes$name)-1
  dataset_link$IDtarget <- match(dataset_link$target, nodes$name)-1
  
  colores <- 'd3.scaleOrdinal() .domain(["General", "Servicios","Hacinamiento", "Materiales"]) .range(["#bebada", "#fb8072", "#80b1d3", "#fdb462"])'
  
  
  sankeyNetwork(Links = dataset_link, Nodes = nodes,
              Source = "IDsource", Target = "IDtarget",
              Value = "cantidad", NodeID = "name", 
               colourScale=colores, NodeGroup="group")
  
}

Caso de Paraguay

plot_sankey(data_pry)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'Calidad de los materiales', 'Hacinamiento + Allegamiento'. You can override using the `.groups` argument.
## `summarise()` has grouped output by 'source'. You can override using the `.groups` argument.
## Links is a tbl_df. Converting to a plain data frame.

Gráfico de barras

ggplot(data = data_arg_tipo) +
  geom_bar(aes(x = reorder(grupo_acum, cantidad), weight = cantidad, 
               fill = deficit2))  + 
  coord_flip() + 
  theme_minimal() + 
  theme(axis.title = element_blank(), 
          legend.position = "bottom")

El gráfico de barras tiene demasiado contenido

plot_deficit_categorias <- function(data) {
  
  dataset <- data %>%
    iadb_clean() %>%
    categorias_de_deficit3() %>%
    group_by(pais_c, deficit2, `Calidad de los materiales`, `Hacinamiento + Allegamiento`, Servicios ) %>%
    summarise(cantidad = sum(factor_ch)) %>%
    ungroup() %>% 
    mutate(grupo_acum = paste0("Materiales: ", `Calidad de los materiales`, 
                               " /  Hacinamiento + Allegamiento: ", `Hacinamiento + Allegamiento`,
                               " / Servicios: ", Servicios )) 
  
  pais <- dataset %>%
    select(pais_c) %>%
    unique() %>%
    .$pais_c
  
  ggplot(data = dataset) +
    geom_bar(aes(x = reorder(grupo_acum, cantidad), weight = cantidad, 
                 fill = factor(deficit2, levels = c("Sin déficit", "Cualitativo", "Cuantitativo"))))  + 
    labs(title = paste0(pais, ": Composición del déficit de vivienda"), 
         caption = "A partir de Harmonized Survey - IDB", 
         fill = "Categorías") +  
    coord_flip() + 
    guides(fill = guide_legend(title.position = "top", nrow = 1)) + 
    scale_fill_manual(values = c("#4daf4a", "#377eb8", "#e41a1c")) + 
    theme_minimal() + 
    theme(axis.title = element_blank(), 
          legend.position = "bottom")
  
}
plot_deficit_categorias(data_arg)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'Calidad de los materiales', 'Hacinamiento + Allegamiento'. You can override using the `.groups` argument.

plot_deficit_categorias(data_bol)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'Calidad de los materiales', 'Hacinamiento + Allegamiento'. You can override using the `.groups` argument.

Efectivamente en bolivia se da un alto déficit cuantitativo de vivienda por Hacinamiento / Allegamiento. Se propone estudiar en detalle el caso, y cargar más años para ser si es un problema de la medición en ese año.

ANEXO:3 Estudio de Bolivia

data_bol2015 <- data_bol
data_bol2013 <- read_dta("harmonized_surveys/BOL_2013m11_BID.dta")
data_bol2014 <- read_dta("harmonized_surveys/BOL_2014m11_BID.dta")
data_bol2016 <- read_dta("harmonized_surveys/BOL_2016m11_BID.dta")
data_bol2017 <- read_dta("harmonized_surveys/BOL_2017m11_BID.dta")
data_bol2018 <- read_dta("harmonized_surveys/BOL_2018m11_BID.dta")

Limpieza de datos de 2015

Veamos si detectamos alguna anormalidad

data_bol_clean <- iadb_clean(data_bol)

Resumen estadístico:

data_bol_clean %>%
  mutate(cm = as.factor(cm), 
         ag = as.factor(ag), 
         cl = as.factor(cl), 
         el = as.factor(el), 
         ha = as.factor(ha), 
         tv = as.factor(tv), 
         db = as.factor(db), 
         deficit2 = as.factor(deficit2)) %>%
  summary()
##     pais_c           region_BID_c   region_c             anio_c    
##  Length:10171       Min.   :3     Length:10171       Min.   :2015  
##  Class :character   1st Qu.:3     Class :character   1st Qu.:2015  
##  Mode  :character   Median :3     Mode  :character   Median :2015  
##                     Mean   :3                        Mean   :2015  
##                     3rd Qu.:3                        3rd Qu.:2015  
##                     Max.   :3                        Max.   :2015  
##                                                                    
##      mes_c        zona_c           idh_ch        factor_ch       clasehog_ch   
##  Min.   :11   Min.   :0.0000   Min.   :    1   Min.   :  63.0   Min.   :1.000  
##  1st Qu.:11   1st Qu.:1.0000   1st Qu.: 2544   1st Qu.: 206.0   1st Qu.:2.000  
##  Median :11   Median :1.0000   Median : 5086   Median : 248.0   Median :2.000  
##  Mean   :11   Mean   :0.7802   Mean   : 5086   Mean   : 296.2   Mean   :2.048  
##  3rd Qu.:11   3rd Qu.:1.0000   3rd Qu.: 7628   3rd Qu.: 345.0   3rd Qu.:2.000  
##  Max.   :11   Max.   :1.0000   Max.   :10171   Max.   :1046.0   Max.   :5.000  
##                                                                                
##   nmiembros_ch      aguared_ch     aguadist_ch    aguamejorada_ch 
##  Min.   : 1.000   Min.   :0.000   Min.   :1.000   Min.   :0.0000  
##  1st Qu.: 2.000   1st Qu.:0.000   1st Qu.:1.000   1st Qu.:1.0000  
##  Median : 4.000   Median :1.000   Median :1.000   Median :1.0000  
##  Mean   : 3.663   Mean   :0.713   Mean   :1.533   Mean   :0.8277  
##  3rd Qu.: 5.000   3rd Qu.:1.000   3rd Qu.:2.000   3rd Qu.:1.0000  
##  Max.   :17.000   Max.   :1.000   Max.   :3.000   Max.   :1.0000  
##                                   NA's   :2335                    
##      luz_ch       banoex_ch         des1_ch          des2_ch      
##  Min.   :0.00   Min.   :0.0000   Min.   :0.0000   Min.   :0.0000  
##  1st Qu.:1.00   1st Qu.:0.0000   1st Qu.:1.0000   1st Qu.:1.0000  
##  Median :1.00   Median :1.0000   Median :1.0000   Median :1.0000  
##  Mean   :0.94   Mean   :0.6825   Mean   :0.8825   Mean   :0.8541  
##  3rd Qu.:1.00   3rd Qu.:1.0000   3rd Qu.:1.0000   3rd Qu.:1.0000  
##  Max.   :1.00   Max.   :1.0000   Max.   :3.0000   Max.   :2.0000  
##                                  NA's   :2485     NA's   :2466    
##     piso_ch          pared_ch         techo_ch         dorm_ch     
##  Min.   :0.0000   Min.   :0.0000   Min.   :0.0000   Min.   :0.000  
##  1st Qu.:1.0000   1st Qu.:1.0000   1st Qu.:1.0000   1st Qu.:1.000  
##  Median :1.0000   Median :1.0000   Median :1.0000   Median :2.000  
##  Mean   :0.8534   Mean   :0.9965   Mean   :0.9484   Mean   :1.695  
##  3rd Qu.:1.0000   3rd Qu.:1.0000   3rd Qu.:1.0000   3rd Qu.:2.000  
##  Max.   :2.0000   Max.   :2.0000   Max.   :2.0000   Max.   :8.000  
##                                                                    
##     vivi2_ch      cm       ag       el          cl       ratio_pers_dorm
##  Min.   :0.0000   0:  76   0:4683   0: 610   0   :1306   Min.   :0.200  
##  1st Qu.:1.0000   1:1523   1:5488   1:9561   1   :6383   1st Qu.:1.333  
##  Median :1.0000   2:8572                     NA's:2482   Median :2.000  
##  Mean   :0.7921                                          Mean   :  Inf  
##  3rd Qu.:1.0000                                          3rd Qu.:3.500  
##  Max.   :1.0000                                          Max.   :  Inf  
##                                                                         
##  ha       tv       db               deficit2   
##  0:5853   0:2115   0:3229   Cualitativo :2580  
##  1:1837   1:8056   1:6942   Cuantitativo:4937  
##  2:2481                     Sin déficit :2654  
##                                                
##                                                
##                                                
## 

Algo muy interesante que se observa es que un tercio de los encuestados no cuenta con baño propio. Llama la atención también la no disponibilidad de agua de red también.

¿Se trata de algo general en Bolivia? ¿o es una anomalía del año de la encuesta?

lista.BOL <- list(data_bol2013, data_bol2014, data_bol2015, data_bol2016, data_bol2017, data_bol2018)

dataBOL_temp <- map(lista.BOL, iadb_clean) %>% #se aplica a todos los df la funcion de variables
  bind_rows() 

Gráfico

plot_deficit_ev(dataBOL_temp)
## `summarise()` has grouped output by 'pais_c', 'deficit2'. You can override using the `.groups` argument.

Este gráfico muestra la constancia de los datos a través de los años.

plot_deficit_categorias(data_bol2014)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'Calidad de los materiales', 'Hacinamiento + Allegamiento'. You can override using the `.groups` argument.

plot_deficit_categorias(data_bol2016)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'Calidad de los materiales', 'Hacinamiento + Allegamiento'. You can override using the `.groups` argument.

plot_deficit_categorias(data_bol2018)
## `summarise()` has grouped output by 'pais_c', 'deficit2', 'Calidad de los materiales', 'Hacinamiento + Allegamiento'. You can override using the `.groups` argument.

En los 3 gráficos, se observa que el hacinamiento + allegamiento es preponderante para la determinación del déficit cuantitativo.

Detalle de hacinamiento + allegamiento

Las 3 variables que componen esta categoría son:
- hacinamiento crítico (en función de la cantidad de habitantes por cuarto)
- tipo de vivienda (¿Puede ser este componente algo cultural?)
- disponibilidad de baño

dataBOL_temp %>%
  filter(deficit2 == "Cuantitativo") %>%
  group_by(anio_c, ha, tv, db ) %>%
  summarise(cantidad = sum(factor_ch)) %>%
  mutate(
    ha = case_when(
      ha == 0 ~ "no tiene", 
      ha == 1 ~ "recuperable", 
      ha == 2 ~ "crítico"), 
    tv = case_when(
      tv == 1 ~ "apta", 
      tv == 0 ~ "no apta"), 
    db = case_when(
      db == 1 ~ "si", 
      db == 0 ~ "no"), 
    
    categorias = paste0("haciamiento: ", ha , "/ tipo vivienda: ", tv, " /baño exclusivo: ", db )) %>%
  
  ggplot() +
    geom_bar(aes(x = reorder(categorias, cantidad), weight = cantidad))  + 
    labs(title = paste0( "Composición del hacinamiento + allegamiento de vivienda"), 
         caption = "A partir de Harmonized Survey - IDB", 
         subtitle =  "Para viviendas con déficit cuantitativo") +  
  facet_wrap(~anio_c, nrow = 3) + 
    coord_flip() + 
    theme_minimal() + 
    theme(axis.title = element_blank(), 
          legend.position = "bottom")
## `summarise()` has grouped output by 'anio_c', 'ha', 'tv'. You can override using the `.groups` argument.

La categoría que es primera llama mucho la atención: hogares en un tipo de vivienda adecuado, y sin hacinamiento (ni siquiera recuperable), comparten baño. ¿se está penalizando alguna cuestión cultural?



Probemos con un dataset que no tiene relacion

library(datasets)
indicador_deficit(iris)
## Error in `[.data.frame`(x, , nombre_variables_list, drop = FALSE) : 
##   undefined columns selected
## Error in select_variables(.): The dataframe is not a harmonized survey