1 1. Carga de Paquetes

suppressPackageStartupMessages({
  library(dplyr); library(ggplot2); library(janitor); library(tidyr)
  library(scales); library(sf); library(viridis); library(ggthemes)
  library(readxl); library(knitr)
})
## Warning: package 'janitor' was built under R version 4.3.3
## Warning: package 'viridis' was built under R version 4.3.3
## Warning: package 'ggthemes' was built under R version 4.3.3
## Warning: package 'readxl' was built under R version 4.3.3
## Warning: package 'knitr' was built under R version 4.3.3

2 2. Carga de Datos (Automática)

# Permite compatibilidad total con RPubs o ejecución local
if (file.exists(params$data_path)) {
  df <- read_excel(path = params$data_path, sheet = params$excel_sheet)
} else if (interactive()) {
  message("Seleccione manualmente el archivo de datos (Excel o CSV)")
  ruta <- file.choose()
  ext <- tools::file_ext(ruta)
  if (ext %in% c("xls", "xlsx")) {
    df <- read_excel(ruta)
  } else {
    df <- read.csv(ruta, check.names = FALSE)
  }
} else if (exists("X1996_2002_valores_nominales_3_")) {
  df <- X1996_2002_valores_nominales_3_
} else {
  stop("No se encontró archivo ni objeto en memoria. Ajuste params$data_path o cargue df.")
}

df <- df %>% janitor::clean_names()
glimpse(df)
## Rows: 168
## Columns: 8
## $ provincias          <chr> "Buenos Aires", "CABA", "Catamarca", "Chaco", "Chu…
## $ ano                 <dbl> 1996, 1996, 1996, 1996, 1996, 1996, 1996, 1996, 19…
## $ reestructuracion    <dbl> 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,…
## $ resultado           <dbl> -290927, 139269, -56502, -45543, -94511, 279055, 1…
## $ deudanac            <dbl> 1112753, 1642020, 154029, 345047, 89683, 608017, 3…
## $ deudaext            <dbl> 1887658, 496080, 110441, 177188, 181164, 303872, 2…
## $ deseq_vertical      <dbl> 0.45364095, 0.08211663, 0.89610956, 0.84352159, 0.…
## $ bancos_privatizados <dbl> 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1,…

3 3. Estadísticos Descriptivos

vars_cuant <- c("resultado","deudanac","deudaext","deseq_vertical")

mode_safe <- function(x) {
  x <- x[!is.na(x)]
  if (length(x)==0) return(NA_real_)
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}
cv_safe <- function(x) {
  m <- mean(x, na.rm = TRUE)
  if (isTRUE(all.equal(m, 0))) return(NA_real_)
  sd(x, na.rm = TRUE)/m*100
}

resumen <- df |>
  summarise(across(all_of(vars_cuant),
                   list(media = ~mean(., na.rm=TRUE),
                        mediana = ~median(., na.rm=TRUE),
                        moda = ~mode_safe(.),
                        desvio = ~sd(., na.rm=TRUE),
                        cv = ~cv_safe(.)),
                   .names = "{.col}_{.fn}"))

resumen

4 4. Tabla Resumen

tabla_resumen <- resumen |>
  pivot_longer(everything(),
               names_to = c("Variable","Medida"),
               names_pattern = "^(.*)_(media|mediana|moda|desvio|cv)$",
               values_to = "Valor") |>
  pivot_wider(names_from = Medida, values_from = Valor) |>
  mutate(across(c(media,mediana,moda,desvio), ~round(.,2)),
         cv = round(cv,2))

knitr::kable(tabla_resumen, digits=2, caption="Medidas descriptivas por variable")
Medidas descriptivas por variable
Variable media mediana moda desvio cv
resultado -47677.61 -11057.00 -290927.00 294430.2 -617.54
deudanac 571047.75 233897.50 51146.00 1893225.5 331.54
deudaext 477861.45 298199.00 1887658.00 848091.5 177.48
deseq_vertical 0.67 0.69 0.45 0.2 29.96

5 5. Gráficos de Variables Cuantitativas

for (v in vars_cuant) {
  p <- ggplot(df, aes(x=.data[[v]])) +
    geom_histogram(bins=20, fill="steelblue", alpha=0.7) +
    theme_minimal() +
    labs(title=paste("Histograma de", v), x=v, y="Frecuencia") +
    theme(plot.title=element_text(hjust=.5))
  print(p)
}

for (v in vars_cuant) {
  p <- ggplot(df, aes(y=.data[[v]])) +
    geom_boxplot(alpha=0.8, fill="lightblue") +
    theme_minimal() +
    labs(title=paste("Diagrama de caja de", v), y=v) +
    theme(plot.title=element_text(hjust=.5))
  print(p)
}

6 6. Gráficos de Variables Cualitativas

ggplot(df, aes(factor(reestructuracion))) +
  geom_bar(fill="orange") +
  theme_minimal() +
  labs(title="Provincias que reestructuraron su deuda", x="Reestructuración (1=Sí, 0=No)", y="Frecuencia")

ggplot(df, aes(factor(bancos_privatizados))) +
  geom_bar(fill="tomato") +
  theme_minimal() +
  labs(title="Bancos privatizados por provincia", x="Privatización (1=Sí, 0=No)", y="Frecuencia")

df |>
  count(reestructuracion) |>
  mutate(pct=n/sum(n)) |>
  ggplot(aes(x="", y=pct, fill=factor(reestructuracion))) +
  geom_col(width=1) +
  coord_polar(theta="y") +
  scale_fill_viridis_d(name="Reestructuración") +
  labs(title="Proporción de reestructuraciones") +
  theme_void()

7 7. Mapa de Promedios por Provincia

promedios <- df |>
  group_by(provincias) |>
  summarise(resultado_prom = mean(resultado, na.rm=TRUE),
            deudanac_prom  = mean(deudanac,  na.rm=TRUE),
            deudaext_prom  = mean(deudaext,  na.rm=TRUE),
            reestruct      = as.integer(any(reestructuracion == 1, na.rm=TRUE)),
            .groups="drop")

arg <- tryCatch(sf::st_read("https://simplemaps.com/static/svg/country/ar/admin1/ar.json", quiet=TRUE),
                error=function(e) NULL)

if (!is.null(arg)) {
  promedios <- promedios |>
    mutate(prov_match = dplyr::recode(provincias,
      "CABA"="Ciudad de Buenos Aires",
      "Neuquen"="Neuquén",
      "Rio Negro"="Río Negro",
      "Tierra del Fuego, Antártida e Islas del Atlántico Sur"="Tierra del Fuego",
      .default=provincias))
  mapa <- arg |> left_join(promedios, by=c("name"="prov_match"))

  ggplot(mapa) +
    geom_sf(aes(fill=resultado_prom), color="white") +
    scale_fill_viridis_c(option="magma", na.value="grey90") +
    theme_minimal() +
    labs(title="Resultado fiscal promedio (1996–2002)", fill="Resultado")
}

8 8. Publicación en RPubs

  1. Knit → Knit to HTML
  2. Luego hacé click en Publish (RPubs).

9 9. Información de sesión

sessionInfo()
## R version 4.3.2 (2023-10-31 ucrt)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 11 x64 (build 26100)
## 
## Matrix products: default
## 
## 
## locale:
## [1] LC_COLLATE=Spanish_Argentina.utf8  LC_CTYPE=Spanish_Argentina.utf8   
## [3] LC_MONETARY=Spanish_Argentina.utf8 LC_NUMERIC=C                      
## [5] LC_TIME=Spanish_Argentina.utf8    
## 
## time zone: America/Buenos_Aires
## tzcode source: internal
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] knitr_1.50        readxl_1.4.5      ggthemes_5.1.0    viridis_0.6.5    
##  [5] viridisLite_0.4.2 sf_1.0-21         scales_1.4.0      tidyr_1.3.1      
##  [9] janitor_2.2.1     ggplot2_4.0.0     dplyr_1.1.4      
## 
## loaded via a namespace (and not attached):
##  [1] sass_0.4.10        utf8_1.2.4         generics_0.1.3     class_7.3-22      
##  [5] KernSmooth_2.23-22 stringi_1.8.3      digest_0.6.33      magrittr_2.0.3    
##  [9] evaluate_1.0.5     grid_4.3.2         timechange_0.2.0   RColorBrewer_1.1-3
## [13] fastmap_1.2.0      cellranger_1.1.0   jsonlite_1.8.8     e1071_1.7-16      
## [17] DBI_1.1.3          gridExtra_2.3      purrr_1.0.2        fansi_1.0.6       
## [21] jquerylib_0.1.4    cli_3.6.2          rlang_1.1.6        units_0.8-5       
## [25] withr_3.0.2        cachem_1.1.0       yaml_2.3.8         tools_4.3.2       
## [29] vctrs_0.6.5        R6_2.5.1           proxy_0.4-27       lifecycle_1.0.4   
## [33] lubridate_1.9.3    classInt_0.4-11    snakecase_0.11.1   stringr_1.5.1     
## [37] pkgconfig_2.0.3    pillar_1.9.0       bslib_0.6.1        gtable_0.3.6      
## [41] Rcpp_1.0.11        glue_1.6.2         xfun_0.52          tibble_3.2.1      
## [45] tidyselect_1.2.1   rstudioapi_0.15.0  farver_2.1.1       htmltools_0.5.8.1 
## [49] labeling_0.4.3     rmarkdown_2.29     compiler_4.3.2     S7_0.2.0