class: center, middle, inverse, title-slide .title[ # Taller 1 ] .subtitle[ ## Introducción a R, Rstudio y el paquete tidyverse ] .author[ ### Carlos DaboĆn ] .date[ ### Septiembre, 2023 ] --- <style> </style> ## Talleres de anĆ”lisis de datos Tras la culminación de cada clase teórica tendremos un taller donde revisaremos algunas maneras de aplicar los mĆ©todos presentados en clase. Para ello nos valdremos de **R** y **Rstudio** Si aĆŗn no lo has hecho: .pull-left[ 1. Descarga e instala [R](https://www.r-project.org/). 2. Luego descarga e instala [RStudio.](https://www.rstudio.com/products/rstudio/) ] .pull-right[ <img src="images/r_rstudio.png" width="40%" height="40%" /> ] <p> </p> <p> </p> *Nota: TambiĆ©n puedes trabajar desde tu buscador accediendo a [Rstudio Cloud](https://www.rstudio.com/products/cloud/). El plan gratuito tiene lĆmites de almancenamiento y procesamiento, pero basta para manejar las asignaturas del curso si lo usas bien.* --- ## R y Rstudio **R** es un ecosistema de software gratuito para anĆ”lisis estadĆstico y la visualización de datos. **RStudio** es un Entorno Integrado de Desarrollo (IDE) que ayuda a los usuarios de R a programar cómodamente. Piensa en **R como el motor** corriendo tu anĆ”lisis, y en **Rstudio como la cabina de control.** .pull-left[ <img src="images/motor.jpg" width="80%" height="80%" /> ] .pull-right[ <img src="images/cabina.jpg" width="80%" height="80%" /> ] --- ## ĀæPor quĆ© R y RStudio? <p> </p> - Es gratis - Comunidad activa e innovación constante (Tip: sigue a [@R4DScommunity](https://twitter.com/R4DScommunity?s=20&t=ALR2omSKksL53wWja8JHxg) en twitter) - Excelentes librarias para el anĆ”lisis y la visualización de datos - Soluciones cómodas para crear [reportes](https://rmarkdown.rstudio.com/gallery.html), [presentaciones](https://arm.rbind.io/slides/xaringan.html#94), libros, [pĆ”ginas web](https://nz-stefan.shinyapps.io/commute-explorer-2/), [APIs](https://www.rplumber.io/), y mĆ”s - Alta demanda en el mercado laboral. --- ## Un vistazo a tu ambiente de trabajo (R Studio IDE) .center[ <img src="images/Rstudio1.png" width="75%" height="75%" /> ] .footnote[From MontanĆ©] --- ## Principios de la programación en R .pull-left[ 1. Todo es un **objeto** 2. Cada objeto tiene un **nombre** y un **valor** 3. Puedes insertar los objetos en **funciones** 4. Las funciónes vienen con **instrucciones** 6. Las funciones son empaquetadas en **librerĆas** 7. Las funciones emiten **alertas sobre posibles errores** <!-- 5. R tiene funciones preinstaladas, pero exĆsten "librerias" de funciones nuevas que puedes descargar gratis. --> <!-- 6. Cualquiera puede crear sus propias funciones, empaquetarlas en su propia libreria y publicar la librerĆa. --> ] .pull-right[ `precio` `precio<-100` `log(precio, base = 10)` <br> `?log` `library(ggplot2)` `log(-1)` ] .footnote[From Mcdermott and Imbens] --- layout:true ##COPY, PASTE, RUN --- .pull-left[ Las matrices son objetos Ćŗtiles en la programación y aplicación de mĆ©todos lineales. Veamos cómo se crea una matriz en R con la función matrix(). ```r ## revisa la documentación ?matrix # data: opcional, require insertar un vector # nrow: nĆŗmero filas de la matriz # ncol: nĆŗmero columnas de la matriz ``` ] .pull-right[ <img src="images/help-matrix.jpg" width="100%" height="80%" /> ] .footnote[From Mcdermott and Imbens] --- .pull-left[ ```r # Creemos un vector con un cero obj_1<-0 # Matriz A: 5x2 llena de ceros A<-matrix(data = obj_1, nrow = 5, ncol = 2) # Veamos la matriz A A ``` ``` ## [,1] [,2] ## [1,] 0 0 ## [2,] 0 0 ## [3,] 0 0 ## [4,] 0 0 ## [5,] 0 0 ``` ] .pull-right[ ```r # Creemos un vector con numeros del 1 al 10 obj_2<-c(1:10) # Matrix B: 5x2 con una sequencia numerica B<-matrix( data = obj_2, nrow = 5, ncol = 2) # Veamos la matriz B B ``` ``` ## [,1] [,2] ## [1,] 1 6 ## [2,] 2 7 ## [3,] 3 8 ## [4,] 4 9 ## [5,] 5 10 ``` ] --- layout: true ## Funciones para anĆ”lisis estadĆstico --- .pull-left[ Este es el código que vamos a correr. ```r x<-c(1:10) # vector x y<-x*2+5 # vector y # Mean mean(x) # Median median(x) # Std. dev. and variance sd(x) var(x) # Min. and max. min(x) max(x) # Correlation/covariance cor(x, y) cov(x, y) # Quartiles and mean of x summary(x) ``` ] .pull-right[ Este es el output que veremos en la consola de Rstudio: ``` ## [1] 5.5 ``` ``` ## [1] 5.5 ``` ``` ## [1] 3.02765 ``` ``` ## [1] 9.166667 ``` ``` ## [1] 1 ``` ``` ## [1] 10 ``` ``` ## [1] 1 ``` ``` ## [1] 18.33333 ``` ``` ## Min. 1st Qu. Median Mean 3rd Qu. Max. ## 1.00 3.25 5.50 5.50 7.75 10.00 ``` ] --- Otras funciones .pull-left[ Este es el código que vamos a correr: ```r # Set seed (pin down random number generation) set.seed(1) # 4 random draws from N(3,5) rnorm(n = 4, mean = 3, sd = sqrt(5)) # CDF for N(0,1) at z=1.96 pnorm(q = 1.96, mean = 0, sd = 1) # Sample 5 draws from x w/ repl. sample( x = x, size = 5, replace = T ) # First and last 3 elements of x head(x, 3) tail(x, 3) ``` ] .pull-right[ Este es el output que veremos en la consola de Rstudio: ``` ## [1] 1.599207 3.410639 1.131478 6.567156 ``` ``` ## [1] 0.9750021 ``` ``` ## [1] 2 3 1 5 5 ``` ``` ## [1] 1 2 3 ``` ``` ## [1] 8 9 10 ``` ] --- Otras funciones .pull-left[ Este es el código que vamos a correr: ```r # Set seed (pin down random number generation) set.seed(1) # 4 random draws from N(3,5) distribucion_normal<-rnorm(n = 4, mean = 3, sd = sqrt(5)) # CDF for N(0,1) at z=1.96 cdf<-pnorm(q = 1.96, mean = 0, sd = 1) # Sample 5 draws from x w/ repl. muestra<-sample( x = x, size = 5, replace = T ) # First and last 3 elements of x head_x<-head(x, 3) tail_x<-tail(x, 3) ``` ] .pull-right[ Este es el output que veremos en la consola de Rstudio: <br> <br> <br> <br> <br> <br> **Ahora no veo el código ĀæQue pasó?** ] --- Otras funciones .pull-left[ Este es el código que vamos a correr: ```r # Set seed (pin down random number generation) set.seed(1) # 4 random draws from N(3,5) distribucion_normal<-rnorm(n = 4, mean = 3, sd = sqrt(5)) # CDF for N(0,1) at z=1.96 cdf<-pnorm(q = 1.96, mean = 0, sd = 1) # Sample 5 draws from x w/ repl. muestra<-sample( x = x, size = 5, replace = T ) # First and last 3 elements of x head_x<-head(x, 3) tail_x<-tail(x, 3) ``` ] .pull-right[ Los objetos que definimos a la derecha fueron guardados al correr el nuevo código. En el panel de estructura de datos queda constancia de ello.  ] --- layout:true ## Importación o lectura de datos --- Algunas de las librerĆas y funciones mĆ”s usadas son: .pull-left[ **LibrerĆa readr** para archivos de formatos variados. * readr::read_csv() * readr::read_delim() * readr::read_rds() **LibrerĆa readxl** para archivos xls, xlsx, o similares. * readxl::read_xlsx() **LibrerĆa haven** para archivos tĆpicos de otros programas (p.e Stata). * haven::read_dta() ] .pull-right[ Leamos algunos archivos disponibles en internet: ```r readr::read_csv("https://github.com/tidyverse/readr/raw/main/inst/extdata/mtcars.csv") ``` ```r readxl::read_excel("../data/news-release-table1-202307.xlsx", range = "A4:K45") ``` ```r haven::read_dta("https://raw.github.com/scunning1975/mixtape/master/titanic.dta") ``` ] --- layout:false ## Paremos para "leer" los datos que vamos a usar Datos del banco mundial sobre PIB, población y esperanza de vida al nacer en su formato original [accede aqui](https://www.bing.com/search?pglt=43&q=world+bank+development+indicators&cvid=c163e5df13924e76b9846b044539d96c&aqs=edge.0.0j69i64j0l7.8635j0j1&FORM=ANAB01&PC=U531) ```r WDI_wide <- read_csv("../data/WDI_extract_data.csv") ``` Datos del banco mundial en formato tidy (hablaremos de donde viene luego): ```r WDI_long <- read_csv("../data/WDI_extract_data_long.csv") ``` La dirección depende del directorio donde estĆ©s ubicado. Escoge tu directorio con Ctrl+Shift+H <img src="images/choose_directory.png" width="40%" height="40%" /> --- layout: true ## Introducción al tidyverse --- ### (Tidy ~ Ordenado) + (verse ~ universo) - El tidyverse es un conjunto de librerĆas en R basados en la misma filosofĆa - Tiene su propia sintaxis y fue pensado para ser mĆ”s intuitivo que las funciones "base" de R ### Promueve usar datos en formato *Tidy*: .pull-left[ 1. Cada variable tiene su propia columna 2. Cada observación tiene su propia fila 3. Cada valor tiene su propia celda ] .pull-right[  ] **ĀæQuĆ© se gana con esto?:** Orden. Hay mil de maneras de tener datos desordenados, pero sólo una manera de tener datos tidy. --- ### Brinda soluciones para cada etapa del anĆ”lisis de datos Cuenta con al menos 8 librerĆas que usaremos a lo largo del curso. .pull-left[  ] .pull-right[ #### Esta semana: -**dplyr** para manipular datos en formato tidy. -**ggplot2** para visualizarlos. ] --- layout: true ## ĀæTidy or not? --- ### World development indicators (World Bank database) <table> <thead> <tr> <th style="text-align:left;"> Country Name </th> <th style="text-align:left;"> Series Name </th> <th style="text-align:left;"> Series Code </th> <th style="text-align:left;"> 1960 [YR1960] </th> <th style="text-align:left;"> 1961 [YR1961] </th> <th style="text-align:left;"> 1962 [YR1962] </th> </tr> </thead> <tbody> <tr> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:left;"> GDP per capita (current US$) </td> <td style="text-align:left;"> NY.GDP.PCAP.CD </td> <td style="text-align:left;"> 59.7732337032148 </td> <td style="text-align:left;"> 59.8608999923829 </td> <td style="text-align:left;"> 58.4580086983139 </td> </tr> <tr> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:left;"> GDP (current US$) </td> <td style="text-align:left;"> NY.GDP.MKTP.CD </td> <td style="text-align:left;"> 537777811.111111 </td> <td style="text-align:left;"> 548888895.555556 </td> <td style="text-align:left;"> 546666677.777778 </td> </tr> <tr> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:left;"> Life expectancy at birth, total (years) </td> <td style="text-align:left;"> SP.DYN.LE00.IN </td> <td style="text-align:left;"> 32.446 </td> <td style="text-align:left;"> 32.962 </td> <td style="text-align:left;"> 33.471 </td> </tr> <tr> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:left;"> Population, total </td> <td style="text-align:left;"> SP.POP.TOTL </td> <td style="text-align:left;"> 8996967 </td> <td style="text-align:left;"> 9169406 </td> <td style="text-align:left;"> 9351442 </td> </tr> </tbody> </table> **Opiniones: Āæes tidy? Āæpor quĆ©?** --- ### World development indicators, version tidy <table> <thead> <tr> <th style="text-align:right;"> year </th> <th style="text-align:left;"> continent_name </th> <th style="text-align:left;"> country_name </th> <th style="text-align:right;"> gdp_pc </th> <th style="text-align:right;"> life_exp </th> <th style="text-align:right;"> population </th> </tr> </thead> <tbody> <tr> <td style="text-align:right;"> 1960 </td> <td style="text-align:left;"> Asia </td> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:right;"> 59.77323 </td> <td style="text-align:right;"> 32.446 </td> <td style="text-align:right;"> 8996967 </td> </tr> <tr> <td style="text-align:right;"> 1961 </td> <td style="text-align:left;"> Asia </td> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:right;"> 59.86090 </td> <td style="text-align:right;"> 32.962 </td> <td style="text-align:right;"> 9169406 </td> </tr> <tr> <td style="text-align:right;"> 1962 </td> <td style="text-align:left;"> Asia </td> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:right;"> 58.45801 </td> <td style="text-align:right;"> 33.471 </td> <td style="text-align:right;"> 9351442 </td> </tr> <tr> <td style="text-align:right;"> 1963 </td> <td style="text-align:left;"> Asia </td> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:right;"> 78.70643 </td> <td style="text-align:right;"> 33.971 </td> <td style="text-align:right;"> 9543200 </td> </tr> <tr> <td style="text-align:right;"> 1964 </td> <td style="text-align:left;"> Asia </td> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:right;"> 82.09531 </td> <td style="text-align:right;"> 34.463 </td> <td style="text-align:right;"> 9744772 </td> </tr> <tr> <td style="text-align:right;"> 1965 </td> <td style="text-align:left;"> Asia </td> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:right;"> 101.10833 </td> <td style="text-align:right;"> 34.948 </td> <td style="text-align:right;"> 9956318 </td> </tr> <tr> <td style="text-align:right;"> 1966 </td> <td style="text-align:left;"> Asia </td> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:right;"> 137.59430 </td> <td style="text-align:right;"> 35.430 </td> <td style="text-align:right;"> 10174840 </td> </tr> <tr> <td style="text-align:right;"> 1967 </td> <td style="text-align:left;"> Asia </td> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:right;"> 160.89843 </td> <td style="text-align:right;"> 35.914 </td> <td style="text-align:right;"> 10399936 </td> </tr> </tbody> </table> --- layout: true ## LibrerĆa dplyr --- Esta librerĆa sirve para manipular de datos en formato tidy (1 variable -> 1 columna, 1 observación -> 1 fila). Para instalarlo en tu equipo: ```r install.packages("dplry") ``` .pull-left[ Para cargar todas las funciones a en tu sesión: ```r library(dplry) ``` Para acceder puntualmente a alguna función: ```r dplyr:: ``` ] .pull-right[  ] .footnote[Con los mismos comandos pueden instalar, cargar, y revisar cualquier otra librerĆa.] --- .pull-left[ **Funciones principales:** - `filter()`: Devlueve los **registros** que cumplen ciertas condiciones. - `select()`: Selecciona, ordena y cambia el nombre de las **variables**. - `arrange()`: Ordena los registros segĆŗn ciertas variables. - `mutate()`: Crea o transforma variables. - `summarise()`: Collapsa todos los registros individuales en uno solo. - `sample_frac()`: Toma muestra aleatoria de las observaciones. - `group_by()`: Condiciona todas las anteriores por grupo. - `lag() & Lead`: Accede al valor de observaciones anteriores o posteriores. ] .pull-right[ **Ejemplos:** ```r filter(data=datos, continent=="Europe") ``` ```r select(data=datos, year,pais=country,poblacion=pop) ``` ```r arrange(data=datos, country,year) ``` ```r mutate(datos, gdp=pop*gdpPercap) ``` ```r summarise(data=filter(data=datos, year==2007), lifeExp=mean(lifeExp)) ``` ```r sample_frac(data=datos,size = 0.5) ``` ```r group_by(data=datos, country,year) ``` ] --- layout: true ## El operador pipe %>% --- Se usa para ubicar **cualquier objeto** a la izquierda en el primer argumento de **cualquier función** a la derecha. Sirve para encadenar el resultado de varias funciones. Hace el código mas legible. .footnote[1) **Short-cut**"Crtl+Shitf+M. 2) Versiones recientes de R incluyen el operador |>, que hace exactamente lo mismo.] --- .pull-left[ **Ejemplos originales:** ```r filter(data=datos, continent=="Europe") ``` ```r select(data=datos,year,pais=country,pob=pop) ``` ```r arrange(data=datos, country, year) ``` ```r mutate(datos, gdp=pop*gdpPercap) ``` ```r summarise(data=filter(data=datos, year==2007), lifeExp=mean(lifeExp)) ``` ] .pull-right[ **Ejemplos con %>% :** ```r datos %>% filter(continent=="Europe") ``` ```r datos %>% select(year,pais=country,poblacion=pop) ``` ```r datos %>% arrange(country,year) ``` ```r datos %>% mutate(gdp=pop*gdpPercap) ``` ```r datos %>% filter(year==2007) %>% summarise(lifeExp=mean(lifeExp)) ``` ] --- layout: true ## dplyr en acción Usa **select()** para darle orden a tus datos .pull-left[ Imagina que te mandan a trabajar con este dataset <table> <thead> <tr> <th style="text-align:left;"> nombre_Terrible </th> <th style="text-align:right;"> VALUE </th> <th style="text-align:left;"> Nombre.Peor </th> </tr> </thead> <tbody> <tr> <td style="text-align:left;"> A </td> <td style="text-align:right;"> -0.01 </td> <td style="text-align:left;"> I </td> </tr> <tr> <td style="text-align:left;"> A </td> <td style="text-align:right;"> 2.40 </td> <td style="text-align:left;"> I </td> </tr> <tr> <td style="text-align:left;"> B </td> <td style="text-align:right;"> 0.76 </td> <td style="text-align:left;"> II </td> </tr> <tr> <td style="text-align:left;"> B </td> <td style="text-align:right;"> -0.80 </td> <td style="text-align:left;"> II </td> </tr> </tbody> </table> ] --- .pull-right[ Puedes hacer tu propia copia del mismo asi ```r datos_terribles<-data.frame( nombre_Terrible=c(rep("A",2),rep("B",2)), VALUE=round(rnorm(4,mean = 0,sd=1),2), Nombre.Peor=c(rep("I",2),rep("II",2)) ) ``` ] --- .pull-right[ Reordena las columnas ```r datos_terribles %>% select(nombre_Terrible, Nombre.Peor,VALUE) ``` ``` ## nombre_Terrible Nombre.Peor VALUE ## 1 A I -1.15 ## 2 A I -0.29 ## 3 B II -0.30 ## 4 B II -0.41 ``` ] --- .pull-right[ Reordena, excluye y cambia los nombres: ```r datos_terribles %>% select(categoria=nombre_Terrible, valor=VALUE) ``` ``` ## categoria valor ## 1 A -1.15 ## 2 A -0.29 ## 3 B -0.30 ## 4 B -0.41 ``` ] --- .pull-right[ Selecciona variables segĆŗn su formato ```r datos_terribles %>% select(where(is.numeric)) ``` ``` ## VALUE ## 1 -1.15 ## 2 -0.29 ## 3 -0.30 ## 4 -0.41 ``` ] --- .pull-right[ Selecciona variables segĆŗn su nombre ```r datos_terribles %>% select(starts_with("nombre")) ``` ``` ## nombre_Terrible Nombre.Peor ## 1 A I ## 2 A I ## 3 B II ## 4 B II ``` ] --- .pull-right[ Usa la función janitor::cleanames() para estandarizar los nombres: ```r library(janitor) # tenes que haberlo instalado install.packages("janitor") datos_terribles %>% clean_names() ``` ``` ## nombre_terrible value nombre_peor ## 1 A -1.15 I ## 2 A -0.29 I ## 3 B -0.30 II ## 4 B -0.41 II ``` ] .footnote[No es de dplyr, pero es una gran herramienta.] --- layout: true ## dplyr en acción --- **Restringe tu analisis a grupos especĆficos:** Muestre el producto per-cĆ”pita de paĆses de las Americas en 2018. .pull-left[ **filter()** ```r WDI_long %>% ## only years where data is available filter(year==2018) %>% ## only North American countries filter(continent_name=="Americas" ) %>% ## only year, country, and per capita gdp select(year,country_name,gdp_pc) ``` ] .pull-right[ ``` ## # A tibble: 46 Ć 3 ## year country_name gdp_pc ## <dbl> <chr> <dbl> ## 1 2018 Antigua and Barbuda 16673. ## 2 2018 Argentina 11633. ## 3 2018 Aruba 30253. ## 4 2018 Bahamas, The 33768. ## 5 2018 Barbados 17745. ## 6 2018 Belize 5001. ## 7 2018 Bermuda 113023. ## 8 2018 Bolivia 3549. ## 9 2018 Brazil 9151. ## 10 2018 British Virgin Islands NA ## # ā¹ 36 more rows ``` ] --- **Crea nuevas variables:** Calcule el producto interno bruto por paĆs y aƱo. .pull-left[ **mutate()** ```r WDI_long %>% ## select variables of your interest select(year,country_name,gdp_pc ,population) %>% ## estimate total GDP by country (in billions). Keep 3 decimals mutate(gdp_bn=round(population*gdp_pc/(10^9),3)) %>% head() ``` ] .pull-right[ ``` ## # A tibble: 6 Ć 5 ## year country_name gdp_pc population gdp_bn ## <dbl> <chr> <dbl> <dbl> <dbl> ## 1 1960 Afghanistan 59.8 8996967 0.538 ## 2 1961 Afghanistan 59.9 9169406 0.549 ## 3 1962 Afghanistan 58.5 9351442 0.547 ## 4 1963 Afghanistan 78.7 9543200 0.751 ## 5 1964 Afghanistan 82.1 9744772 0.8 ## 6 1965 Afghanistan 101. 9956318 1.01 ``` ] --- Obten montos totales, promedios y otras medidas agregadas .pull-left[ **summarise()** ```r WDI_long %>% ## keep year 2018 filter(year==2018) %>% ## estimate total GDP by country (in billions). Keep 3 decimals mutate(gdp_bn=round(population*gdp_pc/(10^9),3)) %>% ## estimate world gdp and world population summarise(life_exp=mean(life_exp, na.rm = T), population=sum(population, na.rm = T), gdp_bn=sum(gdp_bn, na.rm = T)) ``` ] .pull-right[ ``` ## # A tibble: 1 Ć 3 ## life_exp population gdp_bn ## <dbl> <dbl> <dbl> ## 1 72.8 7828350268 87756. ``` ] --- Extiende tus cĆ”lculos a lo largo de diferentes grupos .pull-left[ **group_by()** ```r WDI_long %>% filter(year==2018) %>% group_by(continent_name) %>% summarise(count=n(), mean_life_exp=mean(life_exp,na.rm = T), sd_life_exp=sd(life_exp,na.rm = T)) ``` ] .pull-right[ ``` ## # A tibble: 5 Ć 4 ## continent_name count mean_life_exp sd_life_exp ## <chr> <int> <dbl> <dbl> ## 1 Africa 54 63.8 5.98 ## 2 Americas 46 75.7 3.64 ## 3 Asia 51 74.4 5.04 ## 4 Europe 54 78.7 3.80 ## 5 Oceania 19 73.4 5.99 ``` ] --- CĆ”lcula cambios respecto perĆodos anteriores, o diferencias entre distintas unidades. .pull-left[ **lag()** ```r WDI_long %>% # Un solo paĆs filter(country_name=="Argentina") %>% # Datos ordenados desde mas antiguo a mas reciente arrange(year) %>% # Cambios cada 10 aƱos mutate(change=life_exp-lag(life_exp,10) ) %>% # Muestrame nada mas 4 aƱos filter(year==2018 | year==2008 |year==1998 |year==1988) %>% select(country_name, year, life_exp, change) ``` ] .pull-right[ ``` ## # A tibble: 4 Ć 4 ## country_name year life_exp change ## <chr> <dbl> <dbl> <dbl> ## 1 Argentina 1988 71.2 2.30 ## 2 Argentina 1998 73.2 2.03 ## 3 Argentina 2008 75.0 1.74 ## 4 Argentina 2018 76.5 1.57 ``` ] .footnote[**Ojo:** Tienes que verificar el orden de las observaciones y el nivel de agrupamiento de los datos para no comparar manzans con peras. ] --- **Datos:** Ingreso per cĆ”pita de cada paĆs desde 1950 hasta 2018. **DesafĆo:** ObtĆ©n un resumen de la distribucion del ingreso por continente en el aƱo mas reciente ĀæcĆŗal sintĆ”xis te parece mas clara? .pull-left[ ### (a) Con funciones base de R: ```r aggregate(x = WDI_long[WDI_long$year==max(WDI_long$year),"gdp_pc"] , list(continent = WDI_long[WDI_long$year==max(WDI_long$year),]$continent_name), FUN = function(x) c(min=min(x,na.rm = T), mean=mean(x,na.rm = T), max=max(x,na.rm = T))) %>% as.tibble() ``` ] .pull-right[ ### (b) Con dplyr: ```r WDI_long %>% filter(year==max(year)) %>% group_by(continent_name) %>% summarize(min=min(gdp_pc,na.rm = T), mean=mean(gdp_pc,na.rm = T), max=max(gdp_pc,na.rm = T)) ``` ] --- **Distribucion del ingreso por continente en 2018** .pull-left[ ### (a) Con funciones base de R: ``` ## # A tibble: 5 Ć 2 ## continent gdp_pc[,"min"] [,"mean"] [,"max"] ## <chr> <dbl> <dbl> <dbl> ## 1 Africa 261. 2620. 16199. ## 2 Americas 1272. 18536. 117098. ## 3 Asia 507. 15233. 86118. ## 4 Europe 3663. 33384. 190513. ## 5 Oceania 1655. 13524. 55057. ``` ] .pull-right[ ### (b) Con dplyr: ``` ## # A tibble: 5 Ć 4 ## continent_name min mean max ## <chr> <dbl> <dbl> <dbl> ## 1 Africa 261. 2620. 16199. ## 2 Americas 1272. 18536. 117098. ## 3 Asia 507. 15233. 86118. ## 4 Europe 3663. 33384. 190513. ## 5 Oceania 1655. 13524. 55057. ``` ] --- <!-- layout:true --> <!-- ### REMOVER O RE PLANTEAR --> <!-- **DesafĆo:** ĀæQuĆ© es mayor? ĀæLa varianza del ingreso entre continentes o la varianza lo interno de cada continente? --> <!-- --- --> <!-- .pull-left[ --> <!-- Replica el F-statistic del analisis de varianzas (Test ANOVA): --> <!-- 1. Calcula el numerador: la varianza entre grupos ("between".) --> <!-- 1.1 Calcula el promedio general `\(\bar{X}\)` --> <!-- 1.2 Calcula el promedio de cada grupo `\(\bar{X_j}\)` --> <!-- 1.3 Calcula la varianza entre ambas. --> <!-- 2. Calcula la varianza a lo interno de cada grupo ("within") --> <!-- 3. Produce el F-statistic: retio entre Varbetween/Varwithin --> <!-- ] --> <!-- .pull-right[ --> <!-- `$$F= \frac{\frac{\sum_{j=1}^n N_j(\overline{X}_j-\overline{X})^2}{k-1}}{\frac{\sum\sum(X-\overline{X}_j)^2 }{N-k}}$$` --> <!-- Where: --> <!-- - X: GDP per capita --> <!-- - k: Number of continents or groups --> <!-- - j: Continents --> <!-- - N: Number of countries. --> <!-- ] --> <!-- --- --> <!-- .pull-left[ --> <!-- **CĆ”lcula varianza entre continentes:** --> <!-- ```{r } --> <!-- between_variance<-gapminder_07 %>% # Data similar a WDI --> <!-- ## Calcula la media total --> <!-- mutate(total_mean=mean(lifeExp)) %>% --> <!-- ## Calcula la media por continente con summarise --> <!-- group_by(continent) %>% --> <!-- summarise(n_countries=n(), --> <!-- group_mean=mean(lifeExp), --> <!-- total_mean=first(total_mean)) %>% --> <!-- ungroup() %>% --> <!-- ## Calcula las diferencias between --> <!-- mutate(dif_btw=(group_mean-total_mean)) %>% --> <!-- ## calcula la varianza entre continentes --> <!-- summarise(var_btw=sum(n_countries*dif_btw^2)/(n()-1)) --> <!-- ``` --> <!-- ] --> <!-- .pull-right[ --> <!-- **CĆ”lcula varianza intra-continental** --> <!-- ```{r} --> <!-- within_variance<-gapminder_07 %>% # Data similar a WDI --> <!-- ## Calcula la media por continente con summarise --> <!-- group_by(continent) %>% --> <!-- mutate(group_mean=mean(lifeExp)) %>% --> <!-- ungroup() %>% --> <!-- ## Calcula las diferencias within continents --> <!-- mutate(dif_wtn=(lifeExp-group_mean)) %>% --> <!-- # Calcula varianzas: 1) Eleva las diferencias al cuadrado, --> <!-- ## 2) sumalas, y divide entre tamano de muestra -df --> <!-- summarise(var_wtn=sum(dif_wtn^2)/(n()-5)) --> <!-- ``` --> <!-- ] --> <!-- --- --> <!-- .pull-left[ --> <!-- **Veamos los resultados:** --> <!-- *UsĆ© las funciones print() y paste() para imrprimir los siguientes mensajes: * --> <!-- ```{r, echo=FALSE} --> <!-- # Usa print() y paste() para dejar mensajes personalizados --> <!-- message_1<-paste("La varianza entre continentes es: ", --> <!-- round(between_variance$var_btw,1)) --> <!-- message_2<-paste("La varianza intra-continental es: ", --> <!-- round(within_variance$var_wtn,1)) --> <!-- message_3<-paste("El ratio entre ambas (F-statistic) es:", --> <!-- round(between_variance$var_btw/within_variance$var_wtn)) --> <!-- sum((gapminder_07$lifeExp-mean(gapminder_07$lifeExp))^2)/(nrow(gapminder_07)-1) --> <!-- message_1 --> <!-- message_2 --> <!-- message_3 --> <!-- ``` --> <!-- ] --> <!-- .pull-right[ --> <!-- **Checkeamos resultados con las funciones adecuadas** --> <!-- ```{r} --> <!-- # Compare it with the output in the analysis of variance command --> <!-- aov.model <- aov(lifeExp ~ continent, --> <!-- data = gapminder_07) --> <!-- # Summary of the analysis --> <!-- summary(aov.model) --> <!-- ``` --> <!-- ] --> <!-- --- --> layout: false ## Una imagen vale mas que 1000 *lĆneas de código* <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-55-1.png" width="50%" style="display: block; margin: auto;" /> --- layout: true ## ggplot2() and the grammar of graphics --- <p> </p> <p> </p> .pull-left[ 1. Tu grĆ”fica esta vinculada a los datos mediante coordenadas (aesthetic mappings) 2. Una vez que esas coordenadas estĆ”n definidas puedes presentar tus graficos en distintas formas (geoms), tales como puntos, lineas, barras, etc 3. Puedes agregar tantas capas como gustes a una grafica ] .pull-right[  ] --- layout: false ## Visualizando el PIB per cĆ”pita global Empecemos visualizando la siguiente serie temporal: .pull-left[ ```r gdp_pc_by_year<-WDI_long %>% filter(year>1990) %>% group_by(year) %>% summarise(gdp_pc=weighted.mean(gdp_pc, w=population, na.rm = TRUE)) ``` ] .pull-right[ <table> <thead> <tr> <th style="text-align:right;"> year </th> <th style="text-align:right;"> gdp_pc </th> </tr> </thead> <tbody> <tr> <td style="text-align:right;"> 1991 </td> <td style="text-align:right;"> 4565.059 </td> </tr> <tr> <td style="text-align:right;"> 1992 </td> <td style="text-align:right;"> 4703.727 </td> </tr> <tr> <td style="text-align:right;"> 1993 </td> <td style="text-align:right;"> 4650.490 </td> </tr> <tr> <td style="text-align:right;"> 1994 </td> <td style="text-align:right;"> 4875.684 </td> </tr> <tr> <td style="text-align:right;"> 1995 </td> <td style="text-align:right;"> 5351.510 </td> </tr> <tr> <td style="text-align:right;"> 1996 </td> <td style="text-align:right;"> 5393.152 </td> </tr> <tr> <td style="text-align:right;"> 1997 </td> <td style="text-align:right;"> 5304.659 </td> </tr> <tr> <td style="text-align:right;"> 1998 </td> <td style="text-align:right;"> 5221.885 </td> </tr> <tr> <td style="text-align:right;"> 1999 </td> <td style="text-align:right;"> 5288.473 </td> </tr> <tr> <td style="text-align:right;"> 2000 </td> <td style="text-align:right;"> 5396.982 </td> </tr> </tbody> </table> ] --- layout:false ## Mapeo de coordenadas vs. y aplicacion de geoms .left-threeway[ ```r ggplot(data = gdp_pc_by_year) + * geom_point( * aes(x = year, y = gdp_pc)) + labs(x = "Year", y = "GDP per capita") ``` <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-58-1.png" width="100%" /> ] -- .center-threeway[ ```r ggplot(data = gdp_pc_by_year) + * geom_line( * aes(x = year, y = gdp_pc)) + labs(x = "Year", y = "GDP per capita") ``` <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-59-1.png" width="100%" /> ] -- .right-threeway[ ```r ggplot(data = gdp_pc_by_year, aes(x = year, y = gdp_pc)) + * geom_point()+ * geom_line() + labs(x = "Year", y = "GDP per capita") ``` <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-60-1.png" width="100%" /> ] --- ## Atributos en función de datos y atributos fijos .left-threeway[ ```r ggplot(data = gdp_pc_by_year, aes(x = year, y = gdp_pc)) + *geom_point(aes(color=gdp_pc))+ labs(x = "Year", y = "GDP per capita") ``` <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-61-1.png" width="100%" /> ] -- .center-threeway[ ```r ggplot(data = gdp_pc_by_year, aes(x = year, y = gdp_pc)) + *geom_line(color="navy")+ labs(x = "Year", y = "GDP per capita") ``` <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-62-1.png" width="100%" /> ] -- .right-threeway[ ```r ggplot(data = gdp_pc_by_year, aes(x = year, y = gdp_pc)) + *geom_line(aes(color="navy"))+ labs(x = "Year", y = "GDP per capita") ``` <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-63-1.png" width="100%" /> ] --- layout: false ## Hablemos de la evolucion del ingreso por habitante y la esperanza de vida World development indicators (World Bank) <table> <thead> <tr> <th style="text-align:left;"> country_name </th> <th style="text-align:left;"> country_code </th> <th style="text-align:right;"> year </th> <th style="text-align:right;"> gdp_pc </th> <th style="text-align:right;"> gdp </th> <th style="text-align:right;"> life_exp </th> <th style="text-align:right;"> population </th> <th style="text-align:left;"> continent_name </th> </tr> </thead> <tbody> <tr> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:left;"> AFG </td> <td style="text-align:right;"> 1960 </td> <td style="text-align:right;"> 59.77323 </td> <td style="text-align:right;"> 537777811 </td> <td style="text-align:right;"> 32.446 </td> <td style="text-align:right;"> 8996967 </td> <td style="text-align:left;"> Asia </td> </tr> <tr> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:left;"> AFG </td> <td style="text-align:right;"> 1961 </td> <td style="text-align:right;"> 59.86090 </td> <td style="text-align:right;"> 548888896 </td> <td style="text-align:right;"> 32.962 </td> <td style="text-align:right;"> 9169406 </td> <td style="text-align:left;"> Asia </td> </tr> <tr> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:left;"> AFG </td> <td style="text-align:right;"> 1962 </td> <td style="text-align:right;"> 58.45801 </td> <td style="text-align:right;"> 546666678 </td> <td style="text-align:right;"> 33.471 </td> <td style="text-align:right;"> 9351442 </td> <td style="text-align:left;"> Asia </td> </tr> <tr> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:left;"> AFG </td> <td style="text-align:right;"> 1963 </td> <td style="text-align:right;"> 78.70643 </td> <td style="text-align:right;"> 751111191 </td> <td style="text-align:right;"> 33.971 </td> <td style="text-align:right;"> 9543200 </td> <td style="text-align:left;"> Asia </td> </tr> <tr> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:left;"> AFG </td> <td style="text-align:right;"> 1964 </td> <td style="text-align:right;"> 82.09531 </td> <td style="text-align:right;"> 800000044 </td> <td style="text-align:right;"> 34.463 </td> <td style="text-align:right;"> 9744772 </td> <td style="text-align:left;"> Asia </td> </tr> <tr> <td style="text-align:left;"> Afghanistan </td> <td style="text-align:left;"> AFG </td> <td style="text-align:right;"> 1965 </td> <td style="text-align:right;"> 101.10833 </td> <td style="text-align:right;"> 1006666638 </td> <td style="text-align:right;"> 34.948 </td> <td style="text-align:right;"> 9956318 </td> <td style="text-align:left;"> Asia </td> </tr> </tbody> </table> --- layout:true ## GrĆ”ficos de distribución --- .left-threeway[ Densidad: geom_density ```r ggplot(data=WDI_long_2018, aes(x=gdp_pc))+ * geom_density()+ labs(title="Distribucion de ingreso por habitante") ``` <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-65-1.png" width="100%" /> ] .center-threeway[ Histograma: geom_hist ```r ggplot(data=WDI_long_2018, aes(x=gdp_pc))+ * geom_histogram()+ labs(title="Distribucion de ingreso por habitante") ``` <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-66-1.png" width="100%" /> ] .right-threeway[ Dot chart: geom_dot ```r ggplot(data=WDI_long_2018, aes(x=gdp_pc))+ * geom_dotplot()+ labs(title="Distribucion de ingreso por habitante") ``` <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-67-1.png" width="100%" /> ] --- **Distribución del ingreso por habitante** .pull-left[ ```r # Total ggplot(data=WDI_long_2018, aes(x=gdp_pc))+ # Geom de distribuciones de densidad. Ponemos color en fill afuera de los aesthetics geom_density(fill="gray")+ # Geom de lineas verticales. Requiren el valor del punto de corte # Usamos la palabra "Mean" en punto de corte para que la legenda de la # linea muestre esa palabra (not correct, but effective). * geom_vline(aes(xintercept = mean(gdp_pc),linetype="Mean"))+ labs(title="Distribución completa", linetype="Stats", x="Ingreso por habitante") ``` ] .pull-right[ <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-68-1.png" width="100%" /> ] --- **Distribución del ingreso por habitante, por continente** .pull-left[ ```r # Por continente ggplot(data= WDI_long_2018, aes(x=gdp_pc))+ # Geom de distribucion de densidades, especificando grupos geom_density(aes(fill=continent_name), alpha=0.4) + # Geom de lineas verticales por contienente. Insertamos datos agregados a nivel continente para trazar varias lineas * geom_vline(data= group_by(WDI_long_2018,continent_name) %>% * summarise(gdp_pc=mean(gdp_pc)), * aes(xintercept = gdp_pc,color=continent_name), * show.legend = F)+ scale_x_log10(labels=scales::number_format())+ labs(title="Distribución por continente", fill="Continente", linetype="Stats", x="Ingreso por habitante") ``` ] .pull-right[ <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-69-1.png" width="100%" /> ] --- **Distribución de la esperanza de vida en el mundo** .pull-left[ ```r WDI_long_2018 %>% ggplot(aes(x=life_exp))+ # Geom de distribuciones de densidad. Ponemos color en fill afuera de los aesthetics geom_density(fill="gray")+ # Geom de lineas verticales. Requiren el valor del punto de corte # Usamos la palabra "Mean" en punto de corte para que la legenda de la # linea muestre esa palabra (not correct, but effective). * geom_vline(aes(xintercept = mean(life_exp),linetype="Mean"))+ labs(title="Distribución completa", linetype="Stats", x="Esperanza de vida") ``` ] .pull-right[ <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-70-1.png" width="100%" /> ] --- **Distribución de la esperanza de vida, por continente** .pull-left[ ```r WDI_long_2018 %>% ggplot(aes(x=life_exp))+ # Geom de distribucion de densidades, especificando grupos geom_density(aes(fill=continent_name), alpha=0.4) + # Geom de lineas verticales por contienente # Insertamos datos agregados a nivel continente para trazar varias lineas * geom_vline(data= WDI_long_2018 %>% * group_by(continent_name) %>% * summarise(life_exp=mean(life_exp)), * aes(xintercept = life_exp,color=continent_name), * show.legend = F)+ labs(title="Distribución por continente", fill="Muestra", linetype="Stats", x="Esperanza de vida") ``` ] .pull-right[ <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-71-1.png" width="100%" /> ] --- layout:true ## Relación entre dos variables continuas --- **Define la data, las coordenadas, y la forma** .pull-left[ ```r # Datos y coordenadas ggplot(data=WDI_long_2018, mapping = aes(y=life_exp,x=gdp_pc))+ # Formas o geometrias geom_point()+ labs(x="Gdp Per Capita", y="Life expectancy") ``` ] .pull-right[ <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-72-1.png" width="100%" /> ] --- **AƱade otras formas y haz cambios en el formato** .pull-left[ ```r ggplot(data=WDI_long_2018, mapping = aes(y=life_exp,x=gdp_pc))+ # coordenadas para una geometria especifica geom_point(aes(size=population/1000000, * color=continent_name))+ scale_size_continuous(labels=scales::number_format(), breaks = c(50,500,1000))+ labs(x="Gdp Per Capita", y="Life expectancy",, color="Continent", size="Pop (millions)") ``` ] .pull-right[ <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-73-1.png" width="100%" /> ] --- **Cambiemos la escala de gpd per capita ĀæQuĆ© ganĆ”mos con logs?** .pull-left[ ```r ggplot(data=WDI_long_2018, mapping = aes(y=life_exp,x=gdp_pc))+ # coordenadas para una geometria especifica geom_point(aes(size=population/1000000, color=continent_name))+ scale_size_continuous(labels=scales::number_format(), breaks = c(50,500,1000))+ * scale_x_log10(labels=scales::number_format())+ labs(x="Gdp Per Capita (log scale)", y="Life expectancy",, color="Continent", size="Pop (millions)") ``` ] .pull-right[ <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-74-1.png" width="100%" /> ] --- **La editorial nos pide que hagamos un grĆ”fico accesible para lectores dĆ”ltonicos** .pull-left[ ```r ggplot(data=WDI_long_2018, mapping = aes(y=life_exp,x=gdp_pc))+ # coordenadas para una geometria especifica geom_point(aes(size=population/1000000, * shape=continent_name))+ scale_size_continuous(labels=scales::number_format(), breaks = c(50,500,1000))+ scale_x_log10(labels=scales::number_format())+ labs(x="Gdp Per Capita (log scale)", y="Life expectancy", * shape="Continent", size="Pop (millions)") ``` ] .pull-right[ <img src="Workshop_01_slides_files/figure-html/unnamed-chunk-75-1.png" width="100%" /> ] --- layout: false ### Material de apoyo Fuentes recomendadas para seguir aprendiendo: - [R for Economists video series](https://www.youtube.com/watch?v=dFSPmjSynCs&list=PLcTBLulJV_AIuXCxr__V8XAzWZosMQIfW&index=3) (by Nick Hungtington-Klein) - [R for Data Sicence](https://r4ds.had.co.nz/index.html) (Wickham & Grolemund, 2017) - [Statistical Inference via Data Science](https://moderndive.com/) (Ismay & Kim, 2022) - [Top 50 ggplot2 Visualizations - The Master List](http://r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html#1.%20Correlation) (by Selva Prabhakaran). - [Video: The best stats you'll ever see](https://www.youtube.com/watch?v=hVimVzgtD6w) (by Hans Rosling) - [Video: Statistics without the agonizing pain](https://www.youtube.com/watch?v=5Dnw46eC-0o) (by John Rauser) --- ### Tips .pull-left[ [Usen Chat-GPT](https://openai.com/chatgpt): - PĆdanle que les explique paso a paso bloques de código complicados. - Pidanle recomendaciones sobre que librerĆas y paquetes usar para una tarea especĆfica. - Recuerden que la versión gratuita puede errar, no pidan soluciones complejas de un saque. PĆdanla paso a paso para que puedan cazar los errores. ] .pull-right[ [Usen la ventana de ayuda en R (?funcion)](https://openai.com/chatgpt):  ] <!-- - [R for Economists Basics 1](https://www.youtube.com/watch?v=dFSPmjSynCs&list=PLcTBLulJV_AIuXCxr__V8XAzWZosMQIfW&index=2): Instalación de R y Rstudio, exploración de Rstudio IDE, cómo correr código, y comandos bĆ”sicos. --> <!-- - [R for Economists Basics 2](https://www.youtube.com/watch?v=N6ueivyzK6Y&list=PLcTBLulJV_AIuXCxr__V8XAzWZosMQIfW&index=3): La función help() --> <!-- - [R for Economists Basics 3](https://www.youtube.com/watch?v=J20rEsukxlA&list=PLcTBLulJV_AIuXCxr__V8XAzWZosMQIfW&index=4): Objetos Āæcómo crearlos y actualizarlos? --> <!-- - [R for Economists Basics 4](https://www.youtube.com/watch?v=Kg9UCn7aq9Y&list=PLcTBLulJV_AIuXCxr__V8XAzWZosMQIfW&index=7): Vectores y matrices --> <!-- - [R for Economists Basics 5](https://www.youtube.com/watch?v=ULjXUW5yeDM&list=PLcTBLulJV_AIuXCxr__V8XAzWZosMQIfW&index=6): Data frames parte 1 --> <!-- - [R for Economists Basics 6](https://www.youtube.com/watch?v=N9mLpKAVKME&list=PLcTBLulJV_AIuXCxr__V8XAzWZosMQIfW&index=5): Data frames parte 2 --> <!-- - [R for Economists Basics 7](https://www.youtube.com/watch?v=l5bmDv98zX4&list=PLcTBLulJV_AIuXCxr__V8XAzWZosMQIfW&index=9): Librerias o paquetes --> <!-- - [R for Economists Basics 8](https://www.youtube.com/watch?v=l1lVtEyxnMs&list=PLcTBLulJV_AIuXCxr__V8XAzWZosMQIfW&index=9): AnĆ”lisis descriptivo con una variable --> <!-- - [R for Economists Basics 9](https://www.youtube.com/watch?v=L5WV8KiD8-A&list=PLcTBLulJV_AIuXCxr__V8XAzWZosMQIfW&index=10): AnĆ”lisis bi-variable --> <!-- - [R for Economists Basics 10](https://www.youtube.com/watch?v=pLh2gdHDUZc&list=PLcTBLulJV_AIuXCxr__V8XAzWZosMQIfW&index=11): --> <!-- GrĆ”ficos con R bĆ”se --> --- ### Recuerden 1. Descarguen R y Rstudio e instalen las siguientes librerĆas: ```r # LibrerĆas librerĆas <- c("tidyverse", "readxl", "haven", "lubridate","stringr","gt","stargazer", "causaldata","wooldridge","palmerpenguins","AER", "broom", "modelr","modelsummary", "knitr","rmarkdown","skimr") # Instalar librerias aun no instaladas installed_packages <- librerĆas %in% rownames(installed.packages()) if (any(installed_packages == FALSE)) { install.packages(librerĆas[!installed_packages]) } ``` 2. Les dejĆ© una prĆ”ctica en el proximo slide. 3. El trabajo prĆ”ctico del primer bloque estĆ” publicado. Leerlo puede ser bueno para reforzar lo aprendido esta semana y anticipar el contenido de las próximas clases. --- class: center middle # Fin de primer taller Gracias --- ## PrĆ”ctica Todas las semanas recomendaremos actividades breves para reforzar lo aprendido en los talleres. HabrĆ” un espacio para aclarar dudas que se presentaron al inicio de cada clase presencial. 1. Installen R y Rstudio e intenten replicar todas las diapositivas. Discutimos grĆ”ficos univariados continuos (distribuciones), pero nos faltó discutir grĆ”ficos univariados categóricos. PrĆ”ctiquenlo en casa. 2. Instalen la librerĆa `causaldata'. Al instalarla tendran acceso a varios datasets que usaremos a lo largo del curso 3. Lean la base de datos `causaldata::gapminder`. 4. Creen un data frame con la esperanza de vida promedio de cada continente en 2007. 5. Muestre la esperanza de vida promedio de cada continente en un grĆ”fico de barras (buen tutorial acĆ”). .footnote[Estas prĆ”cticas no son evaluadas, pero sinceramente creemos que los ayudarĆ” a mantenerse al dia con los conceptos. Esto les ayudarĆ” a encarar los trabajos prĆ”cticos de cada bloque con mayor facilidad.]