Clase 1 - Pasos previos

Ctrl + Atl + I para armar bloques de código o fragmentos.

Librerias

library(datos)
## Warning: package 'datos' was built under R version 4.4.3
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.4.3
## 
## Adjuntando el paquete: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.4.3
library(gt)
## Warning: package 'gt' was built under R version 4.4.3
library(tidyverse)
## Warning: package 'tibble' was built under R version 4.4.3
## Warning: package 'tidyr' was built under R version 4.4.3
## Warning: package 'readr' was built under R version 4.4.3
## Warning: package 'purrr' was built under R version 4.4.3
## Warning: package 'stringr' was built under R version 4.4.3
## Warning: package 'forcats' was built under R version 4.4.3
## Warning: package 'lubridate' was built under R version 4.4.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats   1.0.1     ✔ stringr   1.6.0
## ✔ lubridate 1.9.5     ✔ tibble    3.3.1
## ✔ purrr     1.2.2     ✔ tidyr     1.3.2
## ✔ readr     2.2.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(gridExtra)
## 
## Adjuntando el paquete: 'gridExtra'
## 
## The following object is masked from 'package:dplyr':
## 
##     combine
library(kableExtra)
## 
## Adjuntando el paquete: 'kableExtra'
## 
## The following object is masked from 'package:dplyr':
## 
##     group_rows
library(knitr)
## Warning: package 'knitr' was built under R version 4.4.3
options(scipen = 9999) # para ver numeros completos

Levanto la base

Utilizo la convencionada como “datos” Hago algunos controles para ver qué tiene dentro

paises <- paises

str(paises)
## tibble [1,704 × 6] (S3: tbl_df/tbl/data.frame)
##  $ pais             : Factor w/ 142 levels "Afganistán","Albania",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ continente       : Factor w/ 5 levels "África","Américas",..: 3 3 3 3 3 3 3 3 3 3 ...
##  $ anio             : int [1:1704] 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
##  $ esperanza_de_vida: num [1:1704] 28.8 30.3 32 34 36.1 ...
##  $ poblacion        : int [1:1704] 8425333 9240934 10267083 11537966 13079460 14880372 12881816 13867957 16317921 22227415 ...
##  $ pib_per_capita   : num [1:1704] 779 821 853 836 740 ...
summary(paises)
##          pais         continente       anio      esperanza_de_vida
##  Afganistán:  12   África  :624   Min.   :1952   Min.   :23.60    
##  Albania   :  12   Américas:300   1st Qu.:1966   1st Qu.:48.20    
##  Argelia   :  12   Asia    :396   Median :1980   Median :60.71    
##  Angola    :  12   Europa  :360   Mean   :1980   Mean   :59.47    
##  Argentina :  12   Oceanía : 24   3rd Qu.:1993   3rd Qu.:70.85    
##  Australia :  12                  Max.   :2007   Max.   :82.60    
##  (Other)   :1632                                                  
##    poblacion          pib_per_capita    
##  Min.   :     60011   Min.   :   241.2  
##  1st Qu.:   2793664   1st Qu.:  1202.1  
##  Median :   7023596   Median :  3531.8  
##  Mean   :  29601212   Mean   :  7215.3  
##  3rd Qu.:  19585222   3rd Qu.:  9325.5  
##  Max.   :1318683096   Max.   :113523.1  
## 
colnames(paises)
## [1] "pais"              "continente"        "anio"             
## [4] "esperanza_de_vida" "poblacion"         "pib_per_capita"
unique(paises$continente)
## [1] Asia     Europa   África   Américas Oceanía 
## Levels: África Américas Asia Europa Oceanía
unique(paises$pais)
##   [1] Afganistán                      Albania                        
##   [3] Argelia                         Angola                         
##   [5] Argentina                       Australia                      
##   [7] Austria                         Baréin                         
##   [9] Bangladesh                      Bélgica                        
##  [11] Benin                           Bolivia                        
##  [13] Bosnia y Herzegovina            Botswana                       
##  [15] Brasil                          Bulgaria                       
##  [17] Burkina Faso                    Burundi                        
##  [19] Camboya                         Camerún                        
##  [21] Canadá                          República Centroafricana       
##  [23] Chad                            Chile                          
##  [25] China                           Colombia                       
##  [27] Comoras                         República Democrática del Congo
##  [29] Congo                           Costa Rica                     
##  [31] Costa de Marfil                 Croacia                        
##  [33] Cuba                            República Checa                
##  [35] Dinamarca                       Yibuti                         
##  [37] República Dominicana            Ecuador                        
##  [39] Egipto                          El Salvador                    
##  [41] Guinea Ecuatorial               Eritrea                        
##  [43] Etiopía                         Finlandia                      
##  [45] Francia                         Gabón                          
##  [47] Gambia                          Alemania                       
##  [49] Ghana                           Grecia                         
##  [51] Guatemala                       Guinea                         
##  [53] Guinea Bissau                   Haití                          
##  [55] Honduras                        Hong Kong, China               
##  [57] Hungría                         Islandia                       
##  [59] India                           Indonesia                      
##  [61] Irán                            Iraq                           
##  [63] Irlanda                         Israel                         
##  [65] Italia                          Jamaica                        
##  [67] Japón                           Jordania                       
##  [69] Kenia                           Corea, Rep. Dem.               
##  [71] Corea, Rep.                     Kuwait                         
##  [73] Líbano                          Lesoto                         
##  [75] Liberia                         Libia                          
##  [77] Madagascar                      Malaui                         
##  [79] Malasia                         Malí                           
##  [81] Mauritania                      Mauricio                       
##  [83] México                          Mongolia                       
##  [85] Montenegro                      Marruecos                      
##  [87] Mozambique                      Myanmar                        
##  [89] Namibia                         Nepal                          
##  [91] Países Bajos                    Nueva Zelanda                  
##  [93] Nicaragua                       Niger                          
##  [95] Nigeria                         Noruega                        
##  [97] Omán                            Pakistán                       
##  [99] Panamá                          Paraguay                       
## [101] Perú                            Filipinas                      
## [103] Polonia                         Portugal                       
## [105] Puerto Rico                     Reunión                        
## [107] Rumania                         Ruanda                         
## [109] Santo Tomé y Príncipe           Arabia Saudita                 
## [111] Senegal                         Serbia                         
## [113] Sierra Leona                    Singapur                       
## [115] Eslovaquia                      Eslovenia                      
## [117] Somalia                         Sudáfrica                      
## [119] España                          Sri Lanka                      
## [121] Sudán                           Swazilandia                    
## [123] Suecia                          Suiza                          
## [125] Siria                           Taiwán, China                  
## [127] Tanzania                        Tailandia                      
## [129] Togo                            Trinidad y Tobago              
## [131] Túnez                           Turquía                        
## [133] Uganda                          Reino Unido                    
## [135] Estados Unidos                  Uruguay                        
## [137] Venezuela                       Vietnam                        
## [139] Territorios Palestinos          Yemen                          
## [141] Zambia                          Zimbabue                       
## 142 Levels: Afganistán Albania Argelia Angola Argentina Australia ... Zimbabue

Armo los graficos

Vamos a elegir dos paises: Bolivia y Paraguay

seleccion <- paises |>  # ctrl + shitf + M
  filter(continente == "Américas",
         pais %in% c("Bolivia", "Paraguay")) |> 
  ggplot() +
  geom_point(aes(x = anio, y = esperanza_de_vida, colour = pais), size = 2) + 
  geom_line(aes(x = anio, y = esperanza_de_vida,  group = pais,colour = pais), linewidth = 1) +
  scale_x_continuous(
    limits = c(1950,2010),
    breaks = seq(1950,2010, by = 5) ) +
  scale_color_manual(values = c("#880D1E","#F26A8D")) +
  ylim(c(20,80)) +
  labs(
      title = "Esperanza de vida en Bolivia y Paraguay. Años 1952 a 2007",
      subtitle = "evolución quinquenal",
      caption = "Paquete datos, dataset paises",
      x = "año",
      y = "esperanza de vida",
      color = NULL) +
  theme_bw()+ 
  theme(
    legend.position = "bottom")

seleccion

Vamos con la tarea hacia el viernes…

Elegimos los paises del Mercosur.

1.- Graficamos en barras y líneas.

# Datos Mercosur seleccionados

datos_mercosur <- paises |>
  filter(
    pais %in% c("Argentina", "Brasil", "Uruguay")
  ) 

ggplot(datos_mercosur,
       aes(x = factor(anio),
           y = esperanza_de_vida,
           fill = pais)) +
  geom_col(
    width = 0.6,
    position = position_dodge(width = 0.8)
  ) +
  geom_text(
    aes(label = round(esperanza_de_vida,1)),
    position = position_dodge(width = 0.8),
    vjust = -0.3,
    size = 3
  ) +
  coord_cartesian(ylim = c(40, 87)) +
  scale_fill_manual(values = c(
    "Argentina" = "#A8DADC",
    "Brasil"    = "#CDEAC0",
    "Uruguay"   = "#FFD6A5"
  )) +
  labs(
    title = "Esperanza de vida",
    subtitle = "Argentina, Brasil y Uruguay",
    x = "Año",
    y = "Esperanza de vida",
    fill = "País"
  ) +
  theme_bw()

ggplot(datos_mercosur,
       aes(x = factor(anio),
           y = esperanza_de_vida,
           fill = pais)) +
  geom_col(
    width = 0.65,
    position = position_dodge(width = 0.75)
  ) +
  coord_cartesian(ylim = c(40, 85)) +
  scale_fill_manual(values = c(
    "Argentina" = "#5B8FD1",
    "Brasil"    = "#66C2A5",
    "Uruguay"   = "#F4A261"
  )) +
  labs(
    title = "Esperanza de vida al nacer. Mercosur. (el cuadro mas lindo)",
    subtitle = "Argentina, Brasil y Uruguay (estilo moderno)",
    x = NULL,
    y = "Años",
    fill = NULL
  ) +
  theme_minimal(base_size = 13) +
  theme(
    plot.title = element_text(face = "bold", size = 18),
    plot.subtitle = element_text(size = 12),
    legend.position = "top",
    panel.grid.major.x = element_blank(),
    panel.grid.minor = element_blank(),
    axis.title.y = element_text(face = "bold"),
    axis.text = element_text(color = "black")
  )

ggplot(datos_mercosur,
       aes(anio,
           esperanza_de_vida,
           color = pais,
           group = pais)) +

  geom_line(linewidth = 1.2) +
  geom_point(size = 3) +

  scale_color_manual(values = c(
    "Argentina" = "#5B8FD1",
    "Brasil"    = "#66C2A5",
    "Uruguay"   = "#F4A261"
  )) +

  labs(
    title = "Esperanza de vida al nacer. Mercosur.",
    subtitle = "Argentina, Brasil y Uruguay. Gráfico de lineas muy bello.",
    x = NULL,
    y = "Años",
    color = NULL
  ) +

  theme_minimal(base_size = 13) +

  theme(
    legend.position = "top",
    panel.grid.minor = element_blank(),
    panel.grid.major.x = element_blank(),
    plot.title = element_text(face = "bold", size = 18)
  )

Luego mostramos la tabla con los valores.

# Tabla

tabla <- datos_mercosur |>
  select(anio, pais, esperanza_de_vida) |>
  pivot_wider(
    names_from = pais,
    values_from = esperanza_de_vida
  ) |>
  rename(Años = anio)

kable(
  tabla,
  caption = "Esperanza de vida por año",
  digits = 1
) |>
  kable_styling(
    bootstrap_options = c("striped", "hover"),
    full_width = FALSE,
    font_size = 14
  ) |>
  row_spec(0, bold = TRUE)
Esperanza de vida por año
Años Argentina Brasil Uruguay
1952 62.5 50.9 66.1
1957 64.4 53.3 67.0
1962 65.1 55.7 68.3
1967 65.6 57.6 68.5
1972 67.1 59.5 68.7
1977 68.5 61.5 69.5
1982 69.9 63.3 70.8
1987 70.8 65.2 71.9
1992 71.9 67.1 72.8
1997 73.3 69.4 74.2
2002 74.3 71.0 75.3
2007 75.3 72.4 76.4