# PAQUETES
#
library(DT)       # xie2020
library(foreign)  # rcoreteam2020b
library(ggplot2)  # wickham2016
library(reshape2) # wickham2007
library(scales)   # wickham2020
Objetivo
Calcular la tasa de formación de hogares a nivel nacional, estatal y, en su caso, municipal, utilizando los datos contenidos en la ENIGH.
# cat.entidades <- 
#   read.table(
#     file = 'cat_entidades.txt'
#     , sep = '|'
#     , fileEncoding = 'UTF-8'
#     , header = TRUE
#     , stringsAsFactors = FALSE
#     )

# cat.municipios <- 
#   read.table(
#     file = 'cat_municipios.txt'
#     , sep = '|'
#     , fileEncoding = 'UTF-8'
#     , header = TRUE
#     , stringsAsFactors = FALSE
#     )

# LECTURA DATOS FUENTE: CARACTERÍSTICAS DE LOS HOGARES ----
#
# 2022 ----
# 
datos.2022 <- 
  read.dbf(file = './enigh2022_ns_hogares_dbf/hogares.dbf', as.is = TRUE) |>
  transform(AÑO = 2022)

# 2020 ---
# 
datos.2020 <- 
  read.dbf(
    file = './enigh2020_ns_concentradohogar_dbf/concentradohogar.dbf'
    , as.is = TRUE
    )  |>
  transform(AÑO = 2020)

# 2018 ---
# 
datos.2018 <- 
  read.dbf(
    file = './enigh2018_ns_concentradohogar_dbf/concentradohogar.dbf'
    , as.is = TRUE
    )  |>
  transform(AÑO = 2018)

# 2016 ---
# 
datos.2016 <- 
  read.dbf(
    file = './enigh2016_ns_concentradohogar_dbf/concentradohogar.dbf'
    , as.is = TRUE
    )  |>
  transform(AÑO = 2016)

NACIONAL

HOGARES POR AÑO

temp <- 
  rbind(
    datos.2022[,c('AÑO', 'factor')],
    datos.2020[,c('AÑO', 'factor')],
    datos.2018[,c('AÑO', 'factor')],
    datos.2016[,c('AÑO', 'factor')]
    )

temp <- 
  aggregate(
    x = list(HOGARES = temp$factor), by = list(AÑO = factor(temp$AÑO)), FUN = sum
    )

temp$TASA <- NA

for (i in 2:nrow(temp)){
  temp$TASA[i] <- temp$HOGARES[i]/temp$HOGARES[i-1] - 1
}

datatable(
  data = temp |> transform(HOGARES = comma(HOGARES), TASA = percent(TASA))
  , rownames = FALSE
  )
ggplot(data = temp) +
  aes(x = AÑO, y = HOGARES) +
  geom_col() +
  theme_classic() +
  scale_y_continuous(labels = comma)

REFERENCIAS

R Core Team. 2020a. Foreign: Read Data Stored by ’Minitab’, ’s’, ’SAS’, ’SPSS’, ’Stata’, ’Systat’, ’Weka’, ’dBase’, ... https://CRAN.R-project.org/package=foreign.
———. 2020b. R: A Language and Environment for Statistical Computing. Vienna, Austria: R Foundation for Statistical Computing. https://www.R-project.org/.
Wickham, Hadley. 2007. “Reshaping Data with the reshape Package.” Journal of Statistical Software 21 (12): 1–20. http://www.jstatsoft.org/v21/i12/.
———. 2016. Ggplot2: Elegant Graphics for Data Analysis. Springer-Verlag New York. https://ggplot2.tidyverse.org.
Wickham, Hadley, and Dana Seidel. 2020. Scales: Scale Functions for Visualization. https://CRAN.R-project.org/package=scales.
Xie, Yihui, Joe Cheng, and Xianying Tan. 2020. DT: A Wrapper of the JavaScript Library ’DataTables’. https://CRAN.R-project.org/package=DT.