class: left, middle, title-slide .title[ # Visualización de datos aplicada ] .subtitle[ ## Ayudantía práctica en R ] .author[ ###
Joshua Kunst
@jbkunst
] .date[ ### 2022-12-14 ] --- ## Antes de empezar - Repositorio del curso https://github.com/jbkunst/visualizacion-de-datos-aplicada-ayudantia-R encontraremos el programa, clases, datos. - La bibliografía complementaría será _R para ciencia de datos_ https://es.r4ds.hadley.nz/, nos servirá como guía. --- # Temas ayudantía 1. [Visualización](https://es.r4ds.hadley.nz/visualizaci%C3%B3n-de-datos.html) - Codificación de información. - Mapeos de variables. - [{ggplot2}](https://github.com/rstudio/cheatsheets/raw/main/translations/spanish/data-visualization_es.pdf). 2. [Manipulación](https://es.r4ds.hadley.nz/transform.html) - Verbos/acciones. - [{dplyr}](https://github.com/rstudio/cheatsheets/blob/main/translations/spanish/data-transformation_es.pdf). 3. [Comunicación](https://es.r4ds.hadley.nz/r-markdown.html) - Mardown, formatos: html, doc, pdf, etc.: - [{rmarkdown}](https://github.com/rstudio/cheatsheets/raw/main/translations/spanish/rmarkdown_es.pdf). - [{htmlwidgets}](https://gallery.htmlwidgets.org/). --- class: center, inverse, middle # R y Rstudio #### Nuestro ambiente de trabajo_ --- ## R y Rstudio R es el lenguaje de programación que utilizaremos (como C++, python) y RStudio es un IDE para R (como PyCharm para python por ejemplo). Para utilizar R se puede hacer, en un principio, de dos maneras: - Local, Instalar R y RStudio en tu PC. - Utilizar desde la nube con https://posit.cloud/. Más detalles en las diferencias en https://github.com/rivaquiroga/taller-r-doctorado-educacion-2022/blob/master/preparacion-instalacion.md Para conocer un poco más de RStudio https://github.com/rivaquiroga/RLadies-Santiago/blob/master/primeros_pasos_en_R.md. --- ## Setup de PositCloud (ex Rstudio Cloud) <center> <iframe width="784" height="441" src="https://www.youtube.com/embed/B2PJQxRuMFw" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </center> Replicar el repositorio: https://github.com/jbkunst/visualizacion-de-datos-aplicada-ayudantia-R --- class: center, inverse, middle # Visualización de datos #### Análisis exploratorio de datos_ --- ## Análisis Exploratorio de Datos El **Análisis Exploratorio de Datos** se refiere a un ciclo iterativo en el que: - Generas preguntas acerca de tus datos. - Buscas respuestas visualizando, transformando y modelando tus datos. - Usas lo que has aprendido para refinar tus preguntas y/o generar nuevas interrogantes. Lo anterior es un _copy & paste_ desde [R4DS](https://es.r4ds.hadley.nz/an%C3%A1lisis-exploratorio-de-datos-eda.html#an%C3%A1lisis-exploratorio-de-datos-eda). <img src="images/data-science-explore.svg" width="60%" style="display: block; margin: auto;" /> --- ## Visualización Definiremos la visualización, en el contexto de análisis de datos, como una manera de representar/codificar información, y por tanto una herramienta para analizar datos. <img src="images/data-viz.jpg" width="60%" style="display: block; margin: auto;" /> --- ## `ggplot2` <img src="images/viz-mapping-vars.png" width="50%" style="display: block; margin: auto;" /> De forma **general**: ``` ggplot(data = <DATOS>) + <GEOM_FUNCIÓN>(mapping = aes(<MAPEOS>)) ``` --- ## `ggplot2` <img src="images/viz-mapping-vars.png" width="50%" style="display: block; margin: auto;" /> De forma **particular**: ``` ggplot(data = datos) + geom_point(mapping = aes(x = foo, y = bar, size = zaz)) ``` --- ## Hagamos un _copy & paste_ ```r library(datos) library(ggplot2) ggplot(data = millas) + geom_point(mapping = aes(x = cilindrada, y = autopista)) ``` <img src="index_files/figure-html/unnamed-chunk-5-1.svg" width="70%" style="display: block; margin: auto;" /> --- ## Hagamos un _copy & paste_ (v2) ```r library(datos) library(ggplot2) ggplot(millas) + geom_point(aes(cilindrada, autopista)) ``` <img src="index_files/figure-html/unnamed-chunk-6-1.svg" width="70%" style="display: block; margin: auto;" /> --- ## Revisemos los datos ```r library(dplyr) glimpse(millas) ``` ``` ## Rows: 234 ## Columns: 11 ## $ fabricante <chr> "audi", "audi", "audi", "audi", "audi", "audi", "audi", "a… ## $ modelo <chr> "a4", "a4", "a4", "a4", "a4", "a4", "a4", "a4 quattro", "a… ## $ cilindrada <dbl> 1.8, 1.8, 2.0, 2.0, 2.8, 2.8, 3.1, 1.8, 1.8, 2.0, 2.0, 2.8… ## $ anio <int> 1999, 1999, 2008, 2008, 1999, 1999, 2008, 1999, 1999, 2008… ## $ cilindros <int> 4, 4, 4, 4, 6, 6, 6, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8, 8… ## $ transmision <chr> "auto(l5)", "manual(m5)", "manual(m6)", "auto(av)", "auto(… ## $ traccion <chr> "d", "d", "d", "d", "d", "d", "d", "4", "4", "4", "4", "4"… ## $ ciudad <int> 18, 21, 20, 21, 16, 18, 18, 18, 16, 20, 19, 15, 17, 17, 15… ## $ autopista <int> 29, 29, 31, 30, 26, 26, 27, 26, 25, 28, 27, 25, 25, 25, 25… ## $ combustible <chr> "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p"… ## $ clase <chr> "compacto", "compacto", "compacto", "compacto", "compacto"… ``` --- count: false ## Paso a paso .panel1-millas2-auto[ ```r *ggplot( * millas, * aes(cilindrada, autopista) * ) ``` ] .panel2-millas2-auto[ <img src="index_files/figure-html/millas2_auto_01_output-1.svg" width="100%" /> ] --- count: false ## Paso a paso .panel1-millas2-auto[ ```r ggplot( millas, aes(cilindrada, autopista) ) + * geom_point(aes(color = traccion)) ``` ] .panel2-millas2-auto[ <img src="index_files/figure-html/millas2_auto_02_output-1.svg" width="100%" /> ] --- count: false ## Paso a paso .panel1-millas2-auto[ ```r ggplot( millas, aes(cilindrada, autopista) ) + geom_point(aes(color = traccion)) + * geom_smooth() ``` ] .panel2-millas2-auto[ <img src="index_files/figure-html/millas2_auto_03_output-1.svg" width="100%" /> ] --- count: false ## Paso a paso .panel1-millas2-auto[ ```r ggplot( millas, aes(cilindrada, autopista) ) + geom_point(aes(color = traccion)) + geom_smooth() + * scale_color_viridis_d(option = "magma") ``` ] .panel2-millas2-auto[ <img src="index_files/figure-html/millas2_auto_04_output-1.svg" width="100%" /> ] --- count: false ## Paso a paso .panel1-millas2-auto[ ```r ggplot( millas, aes(cilindrada, autopista) ) + geom_point(aes(color = traccion)) + geom_smooth() + scale_color_viridis_d(option = "magma") + * facet_wrap(vars(anio)) ``` ] .panel2-millas2-auto[ <img src="index_files/figure-html/millas2_auto_05_output-1.svg" width="100%" /> ] --- count: false ## Paso a paso .panel1-millas2-auto[ ```r ggplot( millas, aes(cilindrada, autopista) ) + geom_point(aes(color = traccion)) + geom_smooth() + scale_color_viridis_d(option = "magma") + facet_wrap(vars(anio)) + * labs( * title = "Un hermoso título", * subtitle = "Un bello y extenso subtítulo", * caption = "Un texto que nadie mira", * x = "Cilindrada vehículo cc", * y = "Rendimiento en autopista km/lts", * color = "Tipo tracción" * ) ``` ] .panel2-millas2-auto[ <img src="index_files/figure-html/millas2_auto_06_output-1.svg" width="100%" /> ] <style> .panel1-millas2-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-millas2-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-millas2-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- ## A la consola! Ejecutar el script `R/01-script-de-bienvenida.R` (Quizás antes el "R/00-instalar-dependencias.R") --- ## Ejercicio 1 1. Cargue los paquetes `datos`, `ggplot2` y `dplyr`. 1. Ejecute `glimpse(vuelos)`. 1. Objtenga una _muestra_ de 10.000 registros para responder las preguntas utilizando la función `sample_n` (hint (?): `sample_n(vuelos, 1000)`). 1. ¿Cuántos filas/columnas tienen los datos? 1. ¿Cuántos datos son numéricos? 1. Explore la relación entre `distancia` y `tiempo_vuelo`. 1. ¿Qué otras preguntas tienes? ¿Como podríamos obtener QUE vuelo es/son el/los más largos? 1. Reutiliza el código del ejemplo paso a paso para utilizar la función `facet_wrap` con estos datos. --- count: false ## Sirve obtener una **muestra**? .panel1-vuelos_sample-5[ ```r vuelos2 <- sample_n(vuelos, 5000) ggplot(vuelos2, aes(distancia, tiempo_vuelo)) + geom_point(alpha = 0.05, color = "gray60") + geom_smooth(se = FALSE, color = "darkred") + scale_x_continuous(labels = scales::comma) + scale_y_continuous(limits = c(0, 650)) ``` ] .panel2-vuelos_sample-5[ <img src="index_files/figure-html/vuelos_sample_5_01_output-1.svg" width="100%" /> ] --- count: false ## Sirve obtener una **muestra**? .panel1-vuelos_sample-5[ ```r vuelos2 <- sample_n(vuelos, 5000) ggplot(vuelos2, aes(distancia, tiempo_vuelo)) + geom_point(alpha = 0.05, color = "gray60") + geom_smooth(se = FALSE, color = "darkred") + scale_x_continuous(labels = scales::comma) + scale_y_continuous(limits = c(0, 650)) ``` ] .panel2-vuelos_sample-5[ <img src="index_files/figure-html/vuelos_sample_5_02_output-1.svg" width="100%" /> ] --- count: false ## Sirve obtener una **muestra**? .panel1-vuelos_sample-5[ ```r vuelos2 <- sample_n(vuelos, 5000) ggplot(vuelos2, aes(distancia, tiempo_vuelo)) + geom_point(alpha = 0.05, color = "gray60") + geom_smooth(se = FALSE, color = "darkred") + scale_x_continuous(labels = scales::comma) + scale_y_continuous(limits = c(0, 650)) ``` ] .panel2-vuelos_sample-5[ <img src="index_files/figure-html/vuelos_sample_5_03_output-1.svg" width="100%" /> ] --- count: false ## Sirve obtener una **muestra**? .panel1-vuelos_sample-5[ ```r vuelos2 <- sample_n(vuelos, 5000) ggplot(vuelos2, aes(distancia, tiempo_vuelo)) + geom_point(alpha = 0.05, color = "gray60") + geom_smooth(se = FALSE, color = "darkred") + scale_x_continuous(labels = scales::comma) + scale_y_continuous(limits = c(0, 650)) ``` ] .panel2-vuelos_sample-5[ <img src="index_files/figure-html/vuelos_sample_5_04_output-1.svg" width="100%" /> ] --- count: false ## Sirve obtener una **muestra**? .panel1-vuelos_sample-5[ ```r vuelos2 <- sample_n(vuelos, 5000) ggplot(vuelos2, aes(distancia, tiempo_vuelo)) + geom_point(alpha = 0.05, color = "gray60") + geom_smooth(se = FALSE, color = "darkred") + scale_x_continuous(labels = scales::comma) + scale_y_continuous(limits = c(0, 650)) ``` ] .panel2-vuelos_sample-5[ <img src="index_files/figure-html/vuelos_sample_5_05_output-1.svg" width="100%" /> ] <style> .panel1-vuelos_sample-5 { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-vuelos_sample-5 { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-vuelos_sample-5 { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- .center[ <img src="images/ggplot_elements2.png" width="90%" /> ] https://bookdown.org/alapo/learnr/data-visualisation.html --- ## Más información sobre visualización - [Visualización de datos](https://es.r4ds.hadley.nz/visualizaci%C3%B3n-de-datos.html#introducci%C3%B3n-1) en R4DS. - A _simple_ intro to `ggplot2`. [Post](https://www.rforecology.com/post/a-simple-introduction-to-ggplot2/). - Visualización desde el análisis de datos. [Slides](https://jkunst.com/slides/202107-visualizacion-desde-el-analsis-de-datos/index.html). --- class: center, inverse, middle # Transformación y manipulación de datos --- ## Transformación de datos > La visualización es una herramienta importante para la generación de conocimiento; sin embargo, es raro que obtengas los datos exactamente en la forma en que los necesitas. A menudo tendrás que crear algunas variables nuevas o resúmenes, o tal vez solo quieras cambiar el nombre de las variables o reordenar las observaciones para facilitar el trabajo con los datos. Lo anterior es un _copy & paste_ desde [R4DS](https://es.r4ds.hadley.nz/transform.html). --- ## `dplyr` Lo básico En este capítulo, aprenderás las cinco funciones clave de **dplyr** que te permiten resolver la gran mayoría de tus desafíos de manipulación de datos: * Filtrar o elegir las observaciones por sus valores (`filter()` — del inglés filtrar). * Reordenar las filas (`arrange()` — del inglés organizar). * Seleccionar las variables por sus nombres (`select()` — del inglés seleccionar). * Crear nuevas variables con transformaciones de variables existentes (`mutate()` — del inglés mutar o transformar). * Contraer muchos valores en un solo resumen (`summarise()` — del inglés resumir). Todas estas funciones se pueden usar junto con `group_by()` (del inglés _agrupar por_), que cambia el alcance de cada función para que actúe ya no sobre todo el conjunto de datos sino de grupo en grupo. --- ## `dplyr` Lo básico (2) Todos los verbos funcionan de manera similar: 1. El primer argumento es un *data frame*. 2. Los argumentos posteriores describen qué hacer con el *data frame* usando los nombres de las variables (sin comillas). 3. El resultado es un nuevo *data frame*. En conjunto, estas propiedades hacen que sea fácil encadenar varios pasos simples para lograr un resultado complejo. Nuevamente, lo anterior es un _copy & paste_ desde [R4DS](https://es.r4ds.hadley.nz/transform.html). --- background-image: url(images/dplyr/dplyr_filter.jpg) background-size: cover --- ## `filter` Seleccionar Filas <img src="images/dplyr/filter.png" width="70%" style="display: block; margin: auto;" /> --- ## `filter` ejemplo <img src="images/dplyr/filter_example.png" width="80%" style="display: block; margin: auto;" /> --- count: false ## <code>filter</code> Código .panel1-filter-auto[ ```r *storms ``` ] .panel2-filter-auto[ ``` ## # A tibble: 6 × 4 ## storm wind pressure date ## <chr> <dbl> <dbl> <date> ## 1 Alberto 110 1007 2000-08-03 ## 2 Alex 45 1009 1998-07-27 ## 3 Allison 65 1005 1995-06-03 ## 4 Ana 40 1013 1997-06-30 ## 5 Arlene 50 1010 1999-06-11 ## 6 Arthur 45 1010 1996-06-17 ``` ] --- count: false ## <code>filter</code> Código .panel1-filter-auto[ ```r storms |> * filter(storm %in% c("Alberto", "Ana")) ``` ] .panel2-filter-auto[ ``` ## # A tibble: 2 × 4 ## storm wind pressure date ## <chr> <dbl> <dbl> <date> ## 1 Alberto 110 1007 2000-08-03 ## 2 Ana 40 1013 1997-06-30 ``` ] <style> .panel1-filter-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-filter-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-filter-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- ## `select` Seleccionar Columnas <img src="images/dplyr/select.png" width="70%" style="display: block; margin: auto;" /> --- ## `select` ejemplo <img src="images/dplyr/select_example.png" width="80%" style="display: block; margin: auto;" /> --- count: false ## <code>select</code> Código .panel1-select-auto[ ```r *storms ``` ] .panel2-select-auto[ ``` ## # A tibble: 6 × 4 ## storm wind pressure date ## <chr> <dbl> <dbl> <date> ## 1 Alberto 110 1007 2000-08-03 ## 2 Alex 45 1009 1998-07-27 ## 3 Allison 65 1005 1995-06-03 ## 4 Ana 40 1013 1997-06-30 ## 5 Arlene 50 1010 1999-06-11 ## 6 Arthur 45 1010 1996-06-17 ``` ] --- count: false ## <code>select</code> Código .panel1-select-auto[ ```r storms |> * select(storm, pressure) ``` ] .panel2-select-auto[ ``` ## # A tibble: 6 × 2 ## storm pressure ## <chr> <dbl> ## 1 Alberto 1007 ## 2 Alex 1009 ## 3 Allison 1005 ## 4 Ana 1013 ## 5 Arlene 1010 ## 6 Arthur 1010 ``` ] <style> .panel1-select-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-select-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-select-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- ## `arrange` Ordenar Filas <img src="images/dplyr/arrange.png" width="70%" style="display: block; margin: auto;" /> --- ## `arrange` ejemplo <img src="images/dplyr/arrange_example.png" width="80%" style="display: block; margin: auto;" /> --- count: false ## <code>arrange</code> Código .panel1-arrange-auto[ ```r *storms ``` ] .panel2-arrange-auto[ ``` ## # A tibble: 6 × 4 ## storm wind pressure date ## <chr> <dbl> <dbl> <date> ## 1 Alberto 110 1007 2000-08-03 ## 2 Alex 45 1009 1998-07-27 ## 3 Allison 65 1005 1995-06-03 ## 4 Ana 40 1013 1997-06-30 ## 5 Arlene 50 1010 1999-06-11 ## 6 Arthur 45 1010 1996-06-17 ``` ] --- count: false ## <code>arrange</code> Código .panel1-arrange-auto[ ```r storms |> * arrange(wind) ``` ] .panel2-arrange-auto[ ``` ## # A tibble: 6 × 4 ## storm wind pressure date ## <chr> <dbl> <dbl> <date> ## 1 Ana 40 1013 1997-06-30 ## 2 Alex 45 1009 1998-07-27 ## 3 Arthur 45 1010 1996-06-17 ## 4 Arlene 50 1010 1999-06-11 ## 5 Allison 65 1005 1995-06-03 ## 6 Alberto 110 1007 2000-08-03 ``` ] <style> .panel1-arrange-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-arrange-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-arrange-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- background-image: url(images/dplyr/dplyr_mutate.png) background-size: contain --- ## `mutate` Crear (o transformar) Columnas <img src="images/dplyr/mutate.png" width="70%" style="display: block; margin: auto;" /> --- ## `mutate` ejemplo <img src="images/dplyr/mutate_example.png" width="80%" style="display: block; margin: auto;" /> --- count: false ## <code>mutate</code> Código .panel1-mutate-auto[ ```r *storms ``` ] .panel2-mutate-auto[ ``` ## # A tibble: 6 × 4 ## storm wind pressure date ## <chr> <dbl> <dbl> <date> ## 1 Alberto 110 1007 2000-08-03 ## 2 Alex 45 1009 1998-07-27 ## 3 Allison 65 1005 1995-06-03 ## 4 Ana 40 1013 1997-06-30 ## 5 Arlene 50 1010 1999-06-11 ## 6 Arthur 45 1010 1996-06-17 ``` ] --- count: false ## <code>mutate</code> Código .panel1-mutate-auto[ ```r storms |> * mutate( * ratio = pressure/wind, * inverse = 1/ratio * ) ``` ] .panel2-mutate-auto[ ``` ## # A tibble: 6 × 6 ## storm wind pressure date ratio inverse ## <chr> <dbl> <dbl> <date> <dbl> <dbl> ## 1 Alberto 110 1007 2000-08-03 9.15 0.109 ## 2 Alex 45 1009 1998-07-27 22.4 0.0446 ## 3 Allison 65 1005 1995-06-03 15.5 0.0647 ## 4 Ana 40 1013 1997-06-30 25.3 0.0395 ## 5 Arlene 50 1010 1999-06-11 20.2 0.0495 ## 6 Arthur 45 1010 1996-06-17 22.4 0.0446 ``` ] --- count: false ## <code>mutate</code> Código .panel1-mutate-auto[ ```r storms |> mutate( ratio = pressure/wind, inverse = 1/ratio ) |> * mutate(wind = log(wind)) ``` ] .panel2-mutate-auto[ ``` ## # A tibble: 6 × 6 ## storm wind pressure date ratio inverse ## <chr> <dbl> <dbl> <date> <dbl> <dbl> ## 1 Alberto 4.70 1007 2000-08-03 9.15 0.109 ## 2 Alex 3.81 1009 1998-07-27 22.4 0.0446 ## 3 Allison 4.17 1005 1995-06-03 15.5 0.0647 ## 4 Ana 3.69 1013 1997-06-30 25.3 0.0395 ## 5 Arlene 3.91 1010 1999-06-11 20.2 0.0495 ## 6 Arthur 3.81 1010 1996-06-17 22.4 0.0446 ``` ] <style> .panel1-mutate-auto { color: black; width: 32.6666666666667%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-mutate-auto { color: black; width: 65.3333333333333%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-mutate-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- ## `summarise` Resumir Columnas <img src="images/dplyr/summarise.png" width="70%" style="display: block; margin: auto;" /> --- ## `summarise` ejemplo <img src="images/dplyr/summarise_example.png" width="80%" style="display: block; margin: auto;" /> --- count: false ## <code>summarise</code> Código .panel1-summarise-auto[ ```r *pollution ``` ] .panel2-summarise-auto[ ``` ## # A tibble: 6 × 3 ## city size amount ## <chr> <chr> <dbl> ## 1 New York large 23 ## 2 New York small 14 ## 3 London large 22 ## 4 London small 16 ## 5 Beijing large 121 ## 6 Beijing small 56 ``` ] --- count: false ## <code>summarise</code> Código .panel1-summarise-auto[ ```r pollution |> * summarise(median = median(amount)) ``` ] .panel2-summarise-auto[ ``` ## # A tibble: 1 × 1 ## median ## <dbl> ## 1 22.5 ``` ] <style> .panel1-summarise-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-summarise-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-summarise-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- ## `group_by |> summarise` Resumir Columnas por Grupos <img src="images/dplyr/group_by_summarize.png" width="70%" style="display: block; margin: auto;" /> --- ## `group_by |> summarise` ejemplo <img src="images/dplyr/group_by_summarize_example.png" width="80%" style="display: block; margin: auto;" /> --- count: false ## <code>group_by |> summarise</code> Código .panel1-group_by-auto[ ```r *pollution ``` ] .panel2-group_by-auto[ ``` ## # A tibble: 6 × 3 ## city size amount ## <chr> <chr> <dbl> ## 1 New York large 23 ## 2 New York small 14 ## 3 London large 22 ## 4 London small 16 ## 5 Beijing large 121 ## 6 Beijing small 56 ``` ] --- count: false ## <code>group_by |> summarise</code> Código .panel1-group_by-auto[ ```r pollution |> * group_by(city) ``` ] .panel2-group_by-auto[ ``` ## # A tibble: 6 × 3 ## # Groups: city [3] ## city size amount ## <chr> <chr> <dbl> ## 1 New York large 23 ## 2 New York small 14 ## 3 London large 22 ## 4 London small 16 ## 5 Beijing large 121 ## 6 Beijing small 56 ``` ] --- count: false ## <code>group_by |> summarise</code> Código .panel1-group_by-auto[ ```r pollution |> group_by(city) |> * summarise( * mean = mean(amount), * sum = sum(amount), * n = n() * ) ``` ] .panel2-group_by-auto[ ``` ## # A tibble: 3 × 4 ## city mean sum n ## <chr> <dbl> <dbl> <int> ## 1 Beijing 88.5 177 2 ## 2 London 19 38 2 ## 3 New York 18.5 37 2 ``` ] <style> .panel1-group_by-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-group_by-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-group_by-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- count: false ## <code>group_by |> summarise</code> Código <small>(spanish version)</small> .panel1-group_by_spanish-auto[ ```r *pollution ``` ] .panel2-group_by_spanish-auto[ ``` ## # A tibble: 6 × 3 ## city size amount ## <chr> <chr> <dbl> ## 1 New York large 23 ## 2 New York small 14 ## 3 London large 22 ## 4 London small 16 ## 5 Beijing large 121 ## 6 Beijing small 56 ``` ] --- count: false ## <code>group_by |> summarise</code> Código <small>(spanish version)</small> .panel1-group_by_spanish-auto[ ```r pollution |> * group_by(city) ``` ] .panel2-group_by_spanish-auto[ ``` ## # A tibble: 6 × 3 ## # Groups: city [3] ## city size amount ## <chr> <chr> <dbl> ## 1 New York large 23 ## 2 New York small 14 ## 3 London large 22 ## 4 London small 16 ## 5 Beijing large 121 ## 6 Beijing small 56 ``` ] --- count: false ## <code>group_by |> summarise</code> Código <small>(spanish version)</small> .panel1-group_by_spanish-auto[ ```r pollution |> group_by(city) |> * summarise( * promedio = mean(amount), * suma = sum(amount), * conteo = n() * ) ``` ] .panel2-group_by_spanish-auto[ ``` ## # A tibble: 3 × 4 ## city promedio suma conteo ## <chr> <dbl> <dbl> <int> ## 1 Beijing 88.5 177 2 ## 2 London 19 38 2 ## 3 New York 18.5 37 2 ``` ] <style> .panel1-group_by_spanish-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-group_by_spanish-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-group_by_spanish-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- ## Ejercicio 2 <small> 1. Cargue el paquete `tidyverse`, y cree un data frame con columnas `x` e `y`, cada una de las columnas sea 1000 números aleatorios entre -1 y 1 (recuerde la función `runif`). 1. Genere un gráfico de puntos visualizando como se relacionan las variables `x` e `y`. 1. Con la función `mutate` cree una variable `r` que sea igual a `x^2 + y^2`, es decir `\(x^2 + y^2\)`. 1. Utilize la función `if_else` (y `mutate`) para generar una cuarta variable cuya definición es: si `r` es mayor que 1 entonces vale "A", en caso contrario "B". Llame esta variable como `r2`. 1. Ahora vuelva generar el gráfico de 3. pero coloreando el punto de acuerdo a la variable `r2`. 1. Utilice el _combo_ `group_by(r2) |> count()` para contar cuantos son "A" y "B", y luego generar la columna `p = n/sum(n)`. 1. Cree la columna `es_b` que indique con un 1 si el valor de `r2` es "B" y 0 si es "A", para luego crear la columna `convergencia` al aplicar la función `cummean` a la columna `es_b`. 1. con ayuda de la función `row_number()` genere la columna `fila` y haga un gráfico de líneas con `x = fila` e `y = 4 * convergencia`. </small> --- count: false ## Posible solución .panel1-solucion-auto[ ```r *library(tidyverse) ``` ] .panel2-solucion-auto[ ] --- count: false ## Posible solución .panel1-solucion-auto[ ```r library(tidyverse) *set.seed(123) ``` ] .panel2-solucion-auto[ ] --- count: false ## Posible solución .panel1-solucion-auto[ ```r library(tidyverse) set.seed(123) *df <- tibble( * x = runif(1000, -1, 1), * y = runif(1000, -1, 1) *) ``` ] .panel2-solucion-auto[ ] --- count: false ## Posible solución .panel1-solucion-auto[ ```r library(tidyverse) set.seed(123) df <- tibble( x = runif(1000, -1, 1), y = runif(1000, -1, 1) ) *df ``` ] .panel2-solucion-auto[ ``` ## # A tibble: 1,000 × 2 ## x y ## <dbl> <dbl> ## 1 -0.425 -0.453 ## 2 0.577 0.188 ## 3 -0.182 -0.680 ## 4 0.766 0.707 ## 5 0.881 0.695 ## 6 -0.909 -0.0442 ## 7 0.0562 0.547 ## 8 0.785 -0.409 ## 9 0.103 -0.869 ## 10 -0.0868 -0.119 ## # … with 990 more rows ``` ] --- count: false ## Posible solución .panel1-solucion-auto[ ```r library(tidyverse) set.seed(123) df <- tibble( x = runif(1000, -1, 1), y = runif(1000, -1, 1) ) df |> * mutate(r = x^2 + y^2) ``` ] .panel2-solucion-auto[ ``` ## # A tibble: 1,000 × 3 ## x y r ## <dbl> <dbl> <dbl> ## 1 -0.425 -0.453 0.385 ## 2 0.577 0.188 0.368 ## 3 -0.182 -0.680 0.495 ## 4 0.766 0.707 1.09 ## 5 0.881 0.695 1.26 ## 6 -0.909 -0.0442 0.828 ## 7 0.0562 0.547 0.303 ## 8 0.785 -0.409 0.783 ## 9 0.103 -0.869 0.765 ## 10 -0.0868 -0.119 0.0217 ## # … with 990 more rows ``` ] --- count: false ## Posible solución .panel1-solucion-auto[ ```r library(tidyverse) set.seed(123) df <- tibble( x = runif(1000, -1, 1), y = runif(1000, -1, 1) ) df |> mutate(r = x^2 + y^2) |> * mutate(r2 = if_else(r > 1, "A", "B")) ``` ] .panel2-solucion-auto[ ``` ## # A tibble: 1,000 × 4 ## x y r r2 ## <dbl> <dbl> <dbl> <chr> ## 1 -0.425 -0.453 0.385 B ## 2 0.577 0.188 0.368 B ## 3 -0.182 -0.680 0.495 B ## 4 0.766 0.707 1.09 A ## 5 0.881 0.695 1.26 A ## 6 -0.909 -0.0442 0.828 B ## 7 0.0562 0.547 0.303 B ## 8 0.785 -0.409 0.783 B ## 9 0.103 -0.869 0.765 B ## 10 -0.0868 -0.119 0.0217 B ## # … with 990 more rows ``` ] --- count: false ## Posible solución .panel1-solucion-auto[ ```r library(tidyverse) set.seed(123) df <- tibble( x = runif(1000, -1, 1), y = runif(1000, -1, 1) ) df |> mutate(r = x^2 + y^2) |> mutate(r2 = if_else(r > 1, "A", "B")) |> * mutate(es_b = if_else(r2 == "B", 1, 0)) ``` ] .panel2-solucion-auto[ ``` ## # A tibble: 1,000 × 5 ## x y r r2 es_b ## <dbl> <dbl> <dbl> <chr> <dbl> ## 1 -0.425 -0.453 0.385 B 1 ## 2 0.577 0.188 0.368 B 1 ## 3 -0.182 -0.680 0.495 B 1 ## 4 0.766 0.707 1.09 A 0 ## 5 0.881 0.695 1.26 A 0 ## 6 -0.909 -0.0442 0.828 B 1 ## 7 0.0562 0.547 0.303 B 1 ## 8 0.785 -0.409 0.783 B 1 ## 9 0.103 -0.869 0.765 B 1 ## 10 -0.0868 -0.119 0.0217 B 1 ## # … with 990 more rows ``` ] --- count: false ## Posible solución .panel1-solucion-auto[ ```r library(tidyverse) set.seed(123) df <- tibble( x = runif(1000, -1, 1), y = runif(1000, -1, 1) ) df |> mutate(r = x^2 + y^2) |> mutate(r2 = if_else(r > 1, "A", "B")) |> mutate(es_b = if_else(r2 == "B", 1, 0)) |> * mutate(conv = cummean(es_b)) ``` ] .panel2-solucion-auto[ ``` ## # A tibble: 1,000 × 6 ## x y r r2 es_b conv ## <dbl> <dbl> <dbl> <chr> <dbl> <dbl> ## 1 -0.425 -0.453 0.385 B 1 1 ## 2 0.577 0.188 0.368 B 1 1 ## 3 -0.182 -0.680 0.495 B 1 1 ## 4 0.766 0.707 1.09 A 0 0.75 ## 5 0.881 0.695 1.26 A 0 0.6 ## 6 -0.909 -0.0442 0.828 B 1 0.667 ## 7 0.0562 0.547 0.303 B 1 0.714 ## 8 0.785 -0.409 0.783 B 1 0.75 ## 9 0.103 -0.869 0.765 B 1 0.778 ## 10 -0.0868 -0.119 0.0217 B 1 0.8 ## # … with 990 more rows ``` ] --- count: false ## Posible solución .panel1-solucion-auto[ ```r library(tidyverse) set.seed(123) df <- tibble( x = runif(1000, -1, 1), y = runif(1000, -1, 1) ) df |> mutate(r = x^2 + y^2) |> mutate(r2 = if_else(r > 1, "A", "B")) |> mutate(es_b = if_else(r2 == "B", 1, 0)) |> mutate(conv = cummean(es_b)) |> * mutate(fila = row_number()) ``` ] .panel2-solucion-auto[ ``` ## # A tibble: 1,000 × 7 ## x y r r2 es_b conv fila ## <dbl> <dbl> <dbl> <chr> <dbl> <dbl> <int> ## 1 -0.425 -0.453 0.385 B 1 1 1 ## 2 0.577 0.188 0.368 B 1 1 2 ## 3 -0.182 -0.680 0.495 B 1 1 3 ## 4 0.766 0.707 1.09 A 0 0.75 4 ## 5 0.881 0.695 1.26 A 0 0.6 5 ## 6 -0.909 -0.0442 0.828 B 1 0.667 6 ## 7 0.0562 0.547 0.303 B 1 0.714 7 ## 8 0.785 -0.409 0.783 B 1 0.75 8 ## 9 0.103 -0.869 0.765 B 1 0.778 9 ## 10 -0.0868 -0.119 0.0217 B 1 0.8 10 ## # … with 990 more rows ``` ] <style> .panel1-solucion-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-solucion-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-solucion-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- count: false ## Posible solución v2 .panel1-solucion2-auto[ ```r *library(tidyverse) ``` ] .panel2-solucion2-auto[ ] --- count: false ## Posible solución v2 .panel1-solucion2-auto[ ```r library(tidyverse) *set.seed(123) ``` ] .panel2-solucion2-auto[ ] --- count: false ## Posible solución v2 .panel1-solucion2-auto[ ```r library(tidyverse) set.seed(123) *df <- tibble( * x = runif(10000, -1, 1), * y = runif(10000, -1, 1) *) ``` ] .panel2-solucion2-auto[ ] --- count: false ## Posible solución v2 .panel1-solucion2-auto[ ```r library(tidyverse) set.seed(123) df <- tibble( x = runif(10000, -1, 1), y = runif(10000, -1, 1) ) *df ``` ] .panel2-solucion2-auto[ ``` ## # A tibble: 10,000 × 2 ## x y ## <dbl> <dbl> ## 1 -0.425 -0.379 ## 2 0.577 -0.351 ## 3 -0.182 0.741 ## 4 0.766 -0.343 ## 5 0.881 -0.749 ## 6 -0.909 -0.288 ## 7 0.0562 0.861 ## 8 0.785 0.750 ## 9 0.103 0.640 ## 10 -0.0868 -0.956 ## # … with 9,990 more rows ``` ] --- count: false ## Posible solución v2 .panel1-solucion2-auto[ ```r library(tidyverse) set.seed(123) df <- tibble( x = runif(10000, -1, 1), y = runif(10000, -1, 1) ) df |> * mutate( * r = x^2 + y^2, * ri = r < 1, * conv = cummean(ri), * row = row_number() * ) ``` ] .panel2-solucion2-auto[ ``` ## # A tibble: 10,000 × 6 ## x y r ri conv row ## <dbl> <dbl> <dbl> <lgl> <dbl> <int> ## 1 -0.425 -0.379 0.324 TRUE 1 1 ## 2 0.577 -0.351 0.456 TRUE 1 2 ## 3 -0.182 0.741 0.581 TRUE 1 3 ## 4 0.766 -0.343 0.704 TRUE 1 4 ## 5 0.881 -0.749 1.34 FALSE 0.8 5 ## 6 -0.909 -0.288 0.909 TRUE 0.833 6 ## 7 0.0562 0.861 0.745 TRUE 0.857 7 ## 8 0.785 0.750 1.18 FALSE 0.75 8 ## 9 0.103 0.640 0.421 TRUE 0.778 9 ## 10 -0.0868 -0.956 0.922 TRUE 0.8 10 ## # … with 9,990 more rows ``` ] --- count: false ## Posible solución v2 .panel1-solucion2-auto[ ```r library(tidyverse) set.seed(123) df <- tibble( x = runif(10000, -1, 1), y = runif(10000, -1, 1) ) df |> mutate( r = x^2 + y^2, ri = r < 1, conv = cummean(ri), row = row_number() ) |> * ggplot() ``` ] .panel2-solucion2-auto[ <img src="index_files/figure-html/solucion2_auto_06_output-1.svg" width="100%" /> ] --- count: false ## Posible solución v2 .panel1-solucion2-auto[ ```r library(tidyverse) set.seed(123) df <- tibble( x = runif(10000, -1, 1), y = runif(10000, -1, 1) ) df |> mutate( r = x^2 + y^2, ri = r < 1, conv = cummean(ri), row = row_number() ) |> ggplot() + * geom_line(aes(row, 4 * conv)) ``` ] .panel2-solucion2-auto[ <img src="index_files/figure-html/solucion2_auto_07_output-1.svg" width="100%" /> ] --- count: false ## Posible solución v2 .panel1-solucion2-auto[ ```r library(tidyverse) set.seed(123) df <- tibble( x = runif(10000, -1, 1), y = runif(10000, -1, 1) ) df |> mutate( r = x^2 + y^2, ri = r < 1, conv = cummean(ri), row = row_number() ) |> ggplot() + geom_line(aes(row, 4 * conv)) + * geom_hline(yintercept = pi, color = "darkred") ``` ] .panel2-solucion2-auto[ <img src="index_files/figure-html/solucion2_auto_08_output-1.svg" width="100%" /> ] <style> .panel1-solucion2-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-solucion2-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-solucion2-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- count: false ## Posible solución v3 .panel1-solucion3-auto[ ```r *library(tidyverse) ``` ] .panel2-solucion3-auto[ ] --- count: false ## Posible solución v3 .panel1-solucion3-auto[ ```r library(tidyverse) *set.seed(123) ``` ] .panel2-solucion3-auto[ ] --- count: false ## Posible solución v3 .panel1-solucion3-auto[ ```r library(tidyverse) set.seed(123) *tibble( * x = runif(10000, -1, 1), * y = runif(10000, -1, 1) *) ``` ] .panel2-solucion3-auto[ ``` ## # A tibble: 10,000 × 2 ## x y ## <dbl> <dbl> ## 1 -0.425 -0.379 ## 2 0.577 -0.351 ## 3 -0.182 0.741 ## 4 0.766 -0.343 ## 5 0.881 -0.749 ## 6 -0.909 -0.288 ## 7 0.0562 0.861 ## 8 0.785 0.750 ## 9 0.103 0.640 ## 10 -0.0868 -0.956 ## # … with 9,990 more rows ``` ] --- count: false ## Posible solución v3 .panel1-solucion3-auto[ ```r library(tidyverse) set.seed(123) tibble( x = runif(10000, -1, 1), y = runif(10000, -1, 1) ) |> * mutate( * r = x^2 + y^2, * ri = r < 1, * conv = cummean(ri), * row = row_number() * ) ``` ] .panel2-solucion3-auto[ ``` ## # A tibble: 10,000 × 6 ## x y r ri conv row ## <dbl> <dbl> <dbl> <lgl> <dbl> <int> ## 1 -0.425 -0.379 0.324 TRUE 1 1 ## 2 0.577 -0.351 0.456 TRUE 1 2 ## 3 -0.182 0.741 0.581 TRUE 1 3 ## 4 0.766 -0.343 0.704 TRUE 1 4 ## 5 0.881 -0.749 1.34 FALSE 0.8 5 ## 6 -0.909 -0.288 0.909 TRUE 0.833 6 ## 7 0.0562 0.861 0.745 TRUE 0.857 7 ## 8 0.785 0.750 1.18 FALSE 0.75 8 ## 9 0.103 0.640 0.421 TRUE 0.778 9 ## 10 -0.0868 -0.956 0.922 TRUE 0.8 10 ## # … with 9,990 more rows ``` ] --- count: false ## Posible solución v3 .panel1-solucion3-auto[ ```r library(tidyverse) set.seed(123) tibble( x = runif(10000, -1, 1), y = runif(10000, -1, 1) ) |> mutate( r = x^2 + y^2, ri = r < 1, conv = cummean(ri), row = row_number() ) |> * ggplot() ``` ] .panel2-solucion3-auto[ <img src="index_files/figure-html/solucion3_auto_05_output-1.svg" width="100%" /> ] --- count: false ## Posible solución v3 .panel1-solucion3-auto[ ```r library(tidyverse) set.seed(123) tibble( x = runif(10000, -1, 1), y = runif(10000, -1, 1) ) |> mutate( r = x^2 + y^2, ri = r < 1, conv = cummean(ri), row = row_number() ) |> ggplot() + * geom_line(aes(row, 4 * conv)) ``` ] .panel2-solucion3-auto[ <img src="index_files/figure-html/solucion3_auto_06_output-1.svg" width="100%" /> ] --- count: false ## Posible solución v3 .panel1-solucion3-auto[ ```r library(tidyverse) set.seed(123) tibble( x = runif(10000, -1, 1), y = runif(10000, -1, 1) ) |> mutate( r = x^2 + y^2, ri = r < 1, conv = cummean(ri), row = row_number() ) |> ggplot() + geom_line(aes(row, 4 * conv)) + * geom_hline(yintercept = pi, color = "darkred") ``` ] .panel2-solucion3-auto[ <img src="index_files/figure-html/solucion3_auto_07_output-1.svg" width="100%" /> ] --- count: false ## Posible solución v3 .panel1-solucion3-auto[ ```r library(tidyverse) set.seed(123) tibble( x = runif(10000, -1, 1), y = runif(10000, -1, 1) ) |> mutate( r = x^2 + y^2, ri = r < 1, conv = cummean(ri), row = row_number() ) |> ggplot() + geom_line(aes(row, 4 * conv)) + geom_hline(yintercept = pi, color = "darkred") + * scale_x_continuous(labels = scales::comma_format()) ``` ] .panel2-solucion3-auto[ <img src="index_files/figure-html/solucion3_auto_08_output-1.svg" width="100%" /> ] --- count: false ## Posible solución v3 .panel1-solucion3-auto[ ```r library(tidyverse) set.seed(123) tibble( x = runif(10000, -1, 1), y = runif(10000, -1, 1) ) |> mutate( r = x^2 + y^2, ri = r < 1, conv = cummean(ri), row = row_number() ) |> ggplot() + geom_line(aes(row, 4 * conv)) + geom_hline(yintercept = pi, color = "darkred") + scale_x_continuous(labels = scales::comma_format()) + * scale_y_continuous( * sec.axis = sec_axis(trans = ~., breaks = pi, labels = expression(pi)) * ) ``` ] .panel2-solucion3-auto[ <img src="index_files/figure-html/solucion3_auto_09_output-1.svg" width="100%" /> ] <style> .panel1-solucion3-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-solucion3-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-solucion3-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- ## El Pipe (_paip_) `|>` Los pipes son una herramienta poderosa para expresar claramente una secuencia de múltiples operaciones. Hasta aquí, has venido usándolos sin saber cómo funcionan o qué alternativas existen. En este capítulo ya es tiempo de explorarlos en más detalle. En él aprenderás qué alternativas existen, cuándo no deberías utilizarlos y algunas herramientas útiles relacionadas. De forma general veremos que `z |> f()` es equivalente a `f(z)` y en el caso de aplicar parámetros extras tenemos que `z |> g(y)` es `g(x, y)`. En el próximo ejemplo veremos que el **pipe** (`|>` o `%>%`) ayuda a la legibilidad del código. Más en el capítulo [Pipes](https://es.r4ds.hadley.nz/pipes.html) en R4DS. --- count: false ## Ejemplo pipe .panel1-pipe-auto[ ```r *x <- 34 ``` ] .panel2-pipe-auto[ ] --- count: false ## Ejemplo pipe .panel1-pipe-auto[ ```r x <- 34 *tan(cos(sqrt(log(x)))) ``` ] .panel2-pipe-auto[ ``` ## [1] -0.311816 ``` ] --- count: false ## Ejemplo pipe .panel1-pipe-auto[ ```r x <- 34 tan(cos(sqrt(log(x)))) *y <- x ``` ] .panel2-pipe-auto[ ``` ## [1] -0.311816 ``` ] --- count: false ## Ejemplo pipe .panel1-pipe-auto[ ```r x <- 34 tan(cos(sqrt(log(x)))) y <- x *y <- log(y) ``` ] .panel2-pipe-auto[ ``` ## [1] -0.311816 ``` ] --- count: false ## Ejemplo pipe .panel1-pipe-auto[ ```r x <- 34 tan(cos(sqrt(log(x)))) y <- x y <- log(y) *y <- sqrt(y) ``` ] .panel2-pipe-auto[ ``` ## [1] -0.311816 ``` ] --- count: false ## Ejemplo pipe .panel1-pipe-auto[ ```r x <- 34 tan(cos(sqrt(log(x)))) y <- x y <- log(y) y <- sqrt(y) *y <- cos(y) ``` ] .panel2-pipe-auto[ ``` ## [1] -0.311816 ``` ] --- count: false ## Ejemplo pipe .panel1-pipe-auto[ ```r x <- 34 tan(cos(sqrt(log(x)))) y <- x y <- log(y) y <- sqrt(y) y <- cos(y) *y <- tan(y) ``` ] .panel2-pipe-auto[ ``` ## [1] -0.311816 ``` ] --- count: false ## Ejemplo pipe .panel1-pipe-auto[ ```r x <- 34 tan(cos(sqrt(log(x)))) y <- x y <- log(y) y <- sqrt(y) y <- cos(y) y <- tan(y) *y ``` ] .panel2-pipe-auto[ ``` ## [1] -0.311816 ``` ``` ## [1] -0.311816 ``` ] --- count: false ## Ejemplo pipe .panel1-pipe-auto[ ```r x <- 34 tan(cos(sqrt(log(x)))) y <- x y <- log(y) y <- sqrt(y) y <- cos(y) y <- tan(y) y *x ``` ] .panel2-pipe-auto[ ``` ## [1] -0.311816 ``` ``` ## [1] -0.311816 ``` ``` ## [1] 34 ``` ] --- count: false ## Ejemplo pipe .panel1-pipe-auto[ ```r x <- 34 tan(cos(sqrt(log(x)))) y <- x y <- log(y) y <- sqrt(y) y <- cos(y) y <- tan(y) y x |> * log() ``` ] .panel2-pipe-auto[ ``` ## [1] -0.311816 ``` ``` ## [1] -0.311816 ``` ``` ## [1] 3.526361 ``` ] --- count: false ## Ejemplo pipe .panel1-pipe-auto[ ```r x <- 34 tan(cos(sqrt(log(x)))) y <- x y <- log(y) y <- sqrt(y) y <- cos(y) y <- tan(y) y x |> log() |> * sqrt() ``` ] .panel2-pipe-auto[ ``` ## [1] -0.311816 ``` ``` ## [1] -0.311816 ``` ``` ## [1] 1.877861 ``` ] --- count: false ## Ejemplo pipe .panel1-pipe-auto[ ```r x <- 34 tan(cos(sqrt(log(x)))) y <- x y <- log(y) y <- sqrt(y) y <- cos(y) y <- tan(y) y x |> log() |> sqrt() |> * cos() ``` ] .panel2-pipe-auto[ ``` ## [1] -0.311816 ``` ``` ## [1] -0.311816 ``` ``` ## [1] -0.3022616 ``` ] --- count: false ## Ejemplo pipe .panel1-pipe-auto[ ```r x <- 34 tan(cos(sqrt(log(x)))) y <- x y <- log(y) y <- sqrt(y) y <- cos(y) y <- tan(y) y x |> log() |> sqrt() |> cos() |> * tan() ``` ] .panel2-pipe-auto[ ``` ## [1] -0.311816 ``` ``` ## [1] -0.311816 ``` ``` ## [1] -0.311816 ``` ] <style> .panel1-pipe-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-pipe-auto { color: black; width: 49%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-pipe-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- class: center, inverse, middle # rmarkdown #### Comunicar resultados_ --- ## Comunicar resultados https://es.r4ds.hadley.nz/introducci%C3%B3n-18.html Hasta aquí, hemos aprendido a usar las herramientas para importar tus datos en R, ordenarlos de una manera conveniente para el análisis, y luego interpretarlos a través de su transformación, visualización y modelado. <img src="images/data-science-communicate.svg" width="60%" style="display: block; margin: auto;" /> --- ## {rmarkdown} Revisar https://garrettgman.github.io/rmarkdown/index.html - R Markdown provee un marco de escritura para ciencia de datos. - Combina tu código, sus resultados y tus comentarios. - Los documentos de R Markdown son **reproducibles**. - Soportan varios formatos de salida tales como PDFs, archivos de Word, presentaciones y más. --- ## Ejemplo .Rmd (<small>rmarkdown/diamond-sizes.Rmd</small>) .pull-left[ <small> ```` --- title: "Tamaño de los diamantes" author: "Nostros" date: "2016-08-25" output: html_document: default word_document: default pdf_document: default --- ```{r setup, include = FALSE} library(datos) library(ggplot2) library(dplyr) pequenios <- diamantes %>% filter(quilate <= 2.5) ``` Tenemos datos respecto de `r nrow(diamantes)` diamantes. Únicamente `r nrow(diamantes) - nrow(pequenios)` son mayores a 2,5 quilates. La distribución de los diamantes pequeños se muestra a continuación: ```{r, echo = FALSE, message=FALSE} pequenios %>% ggplot(aes(quilate)) + geom_histogram() ``` ```` </small> ] .pull-right[ Contiene tres tipos importantes de contenido: 1. Un encabezado YAML (opcional) rodeado de `---`, Parámetros generales. 1. __Bloques__ de código de R rodeados de ```` ``` ````. 1. Texto mezclado con formateos de texto simple como `# Encabezado`, `_itálicas_`, `**negrita**`, etc.. ] --- # Formatos https://garrettgman.github.io/rmarkdown/formats.html <img src="images/RMarkdownFlow.png" width="60%" style="display: block; margin: auto;" /> 1. Documentos: html, word, pdf, y otros. 1. Slides - [Xaringan](https://slides.yihui.org/xaringan/). - [reavealJS](https://garrettgman.github.io/rmarkdown/revealjs_presentation_format.html), (ejemplo .Rmd [acá](https://github.com/rstudio/revealjs/blob/main/examples/simple.Rmd)) 1. Dashboard con [flexdashboard](https://pkgs.rstudio.com/flexdashboard/index.html). 1. Libros, páginas web, blogs, etc, etc. --- # Ejercicio 3 1. Crea un nuevo notebook usando File > New File > R Notebook. Lee las instrucciones. Practica ejecutando los bloques. Verifica que puedes modificar el código, re-ejecútalo, y observa la salida modificada. 2. Crea un nuevo documento R Markdown con File > New File > R Markdown… Haz clic en el icono apropiado de Knit. Haz Knit usando el atajo de teclado apropiado. Verifica que puedes modificar el input y la actualización del output. 3. Compara y contrasta el notebook de R con los archivos de R markdown que has creado antes. ¿Cómo son similares los outputs? ¿Cómo son diferentes? ¿Cómo son similares los inputs? ¿En qué se diferencian? ¿Qué ocurre si copias el encabezado YAML de uno al otro? --- ## HTMLWidgets (extensión/complemento) HTMLWidgets son un tipo de paquetes que nos permiten realizar visualizaciones en HTML las cuales se pueden usar en (1) consola, (2) integrar con rmarkdown y también (3) shiny. Existen una gran cantida de paquetes https://gallery.htmlwidgets.org/, y nos sirven para complementar nuestra aplicación. - https://plotly.com/r/ - https://jkunst.com/highcharter/ - https://echarts4r.john-coene.com/ - https://rstudio.github.io/leaflet/ - https://rstudio.github.io/DT/ Ejemplo de uso de script `03-clase-script-htmlwidgets.R`. --- count: false ## Antes, un poco de {ggplot2} .panel1-ggplot2-auto[ ```r *library(ggplot2) ``` ] .panel2-ggplot2-auto[ ] --- count: false ## Antes, un poco de {ggplot2} .panel1-ggplot2-auto[ ```r library(ggplot2) *data(iris) ``` ] .panel2-ggplot2-auto[ ] --- count: false ## Antes, un poco de {ggplot2} .panel1-ggplot2-auto[ ```r library(ggplot2) data(iris) *ggplot(iris, aes(Sepal.Length, Sepal.Width)) ``` ] .panel2-ggplot2-auto[ <img src="index_files/figure-html/ggplot2_auto_03_output-1.svg" width="100%" /> ] --- count: false ## Antes, un poco de {ggplot2} .panel1-ggplot2-auto[ ```r library(ggplot2) data(iris) ggplot(iris, aes(Sepal.Length, Sepal.Width)) + * geom_point(aes(color = Species), size = 2.5) ``` ] .panel2-ggplot2-auto[ <img src="index_files/figure-html/ggplot2_auto_04_output-1.svg" width="100%" /> ] --- count: false ## Antes, un poco de {ggplot2} .panel1-ggplot2-auto[ ```r library(ggplot2) data(iris) ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point(aes(color = Species), size = 2.5) + * scale_color_viridis_d(end = .9) ``` ] .panel2-ggplot2-auto[ <img src="index_files/figure-html/ggplot2_auto_05_output-1.svg" width="100%" /> ] --- count: false ## Antes, un poco de {ggplot2} .panel1-ggplot2-auto[ ```r library(ggplot2) data(iris) ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point(aes(color = Species), size = 2.5) + scale_color_viridis_d(end = .9) + * geom_smooth(method = "lm") ``` ] .panel2-ggplot2-auto[ <img src="index_files/figure-html/ggplot2_auto_06_output-1.svg" width="100%" /> ] --- count: false ## Antes, un poco de {ggplot2} .panel1-ggplot2-auto[ ```r library(ggplot2) data(iris) ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point(aes(color = Species), size = 2.5) + scale_color_viridis_d(end = .9) + geom_smooth(method = "lm") + * facet_wrap(vars(Species)) ``` ] .panel2-ggplot2-auto[ <img src="index_files/figure-html/ggplot2_auto_07_output-1.svg" width="100%" /> ] --- count: false ## Antes, un poco de {ggplot2} .panel1-ggplot2-auto[ ```r library(ggplot2) data(iris) ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point(aes(color = Species), size = 2.5) + scale_color_viridis_d(end = .9) + geom_smooth(method = "lm") + facet_wrap(vars(Species)) + * theme_minimal() ``` ] .panel2-ggplot2-auto[ <img src="index_files/figure-html/ggplot2_auto_08_output-1.svg" width="100%" /> ] <style> .panel1-ggplot2-auto { color: black; width: 38.6060606060606%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-ggplot2-auto { color: black; width: 59.3939393939394%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-ggplot2-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- count: false ## {plotly} .panel1-plotly-auto[ ```r *library(ggplot2) ``` ] .panel2-plotly-auto[ ] --- count: false ## {plotly} .panel1-plotly-auto[ ```r library(ggplot2) *library(plotly) ``` ] .panel2-plotly-auto[ ] --- count: false ## {plotly} .panel1-plotly-auto[ ```r library(ggplot2) library(plotly) *data(iris) ``` ] .panel2-plotly-auto[ ] --- count: false ## {plotly} .panel1-plotly-auto[ ```r library(ggplot2) library(plotly) data(iris) *p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) ``` ] .panel2-plotly-auto[ ] --- count: false ## {plotly} .panel1-plotly-auto[ ```r library(ggplot2) library(plotly) data(iris) p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + * geom_point(aes(color = Species), size = 2.5) ``` ] .panel2-plotly-auto[ ] --- count: false ## {plotly} .panel1-plotly-auto[ ```r library(ggplot2) library(plotly) data(iris) p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point(aes(color = Species), size = 2.5) + * scale_color_viridis_d(end = .9) ``` ] .panel2-plotly-auto[ ] --- count: false ## {plotly} .panel1-plotly-auto[ ```r library(ggplot2) library(plotly) data(iris) p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point(aes(color = Species), size = 2.5) + scale_color_viridis_d(end = .9) + * geom_smooth(method = "lm") ``` ] .panel2-plotly-auto[ ] --- count: false ## {plotly} .panel1-plotly-auto[ ```r library(ggplot2) library(plotly) data(iris) p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point(aes(color = Species), size = 2.5) + scale_color_viridis_d(end = .9) + geom_smooth(method = "lm") + * facet_wrap(vars(Species)) ``` ] .panel2-plotly-auto[ ] --- count: false ## {plotly} .panel1-plotly-auto[ ```r library(ggplot2) library(plotly) data(iris) p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point(aes(color = Species), size = 2.5) + scale_color_viridis_d(end = .9) + geom_smooth(method = "lm") + facet_wrap(vars(Species)) + * theme_minimal() ``` ] .panel2-plotly-auto[ ] --- count: false ## {plotly} .panel1-plotly-auto[ ```r library(ggplot2) library(plotly) data(iris) p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point(aes(color = Species), size = 2.5) + scale_color_viridis_d(end = .9) + geom_smooth(method = "lm") + facet_wrap(vars(Species)) + theme_minimal() *ggplotly(p) ``` ] .panel2-plotly-auto[
] <style> .panel1-plotly-auto { color: black; width: 38.6060606060606%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-plotly-auto { color: black; width: 59.3939393939394%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-plotly-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- count: false ## {highcharter} .panel1-highcharter-auto[ ```r *library(highcharter) ``` ] .panel2-highcharter-auto[ ] --- count: false ## {highcharter} .panel1-highcharter-auto[ ```r library(highcharter) *library(forecast) ``` ] .panel2-highcharter-auto[ ] --- count: false ## {highcharter} .panel1-highcharter-auto[ ```r library(highcharter) library(forecast) *data("AirPassengers") ``` ] .panel2-highcharter-auto[ ] --- count: false ## {highcharter} .panel1-highcharter-auto[ ```r library(highcharter) library(forecast) data("AirPassengers") *modelo <- forecast(auto.arima(AirPassengers)) ``` ] .panel2-highcharter-auto[ ] --- count: false ## {highcharter} .panel1-highcharter-auto[ ```r library(highcharter) library(forecast) data("AirPassengers") modelo <- forecast(auto.arima(AirPassengers)) *hchart(modelo) ``` ] .panel2-highcharter-auto[
] --- count: false ## {highcharter} .panel1-highcharter-auto[ ```r library(highcharter) library(forecast) data("AirPassengers") modelo <- forecast(auto.arima(AirPassengers)) hchart(modelo) |> * hc_add_theme(hc_theme_hcrt()) ``` ] .panel2-highcharter-auto[
] --- count: false ## {highcharter} .panel1-highcharter-auto[ ```r library(highcharter) library(forecast) data("AirPassengers") modelo <- forecast(auto.arima(AirPassengers)) hchart(modelo) |> hc_add_theme(hc_theme_hcrt()) |> * hc_navigator(enabled = TRUE) ``` ] .panel2-highcharter-auto[
] --- count: false ## {highcharter} .panel1-highcharter-auto[ ```r library(highcharter) library(forecast) data("AirPassengers") modelo <- forecast(auto.arima(AirPassengers)) hchart(modelo) |> hc_add_theme(hc_theme_hcrt()) |> hc_navigator(enabled = TRUE) |> * hc_rangeSelector(enabled = TRUE) ``` ] .panel2-highcharter-auto[
] --- count: false ## {highcharter} .panel1-highcharter-auto[ ```r library(highcharter) library(forecast) data("AirPassengers") modelo <- forecast(auto.arima(AirPassengers)) hchart(modelo) |> hc_add_theme(hc_theme_hcrt()) |> hc_navigator(enabled = TRUE) |> hc_rangeSelector(enabled = TRUE) |> * hc_title(text = "Proyección") ``` ] .panel2-highcharter-auto[
] <style> .panel1-highcharter-auto { color: black; width: 38.6060606060606%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-highcharter-auto { color: black; width: 59.3939393939394%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-highcharter-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- count: false ## Antes, unos datos .panel1-sismos-auto[ ```r *library(rvest) # descargar datos de paginas web ``` ] .panel2-sismos-auto[ ] --- count: false ## Antes, unos datos .panel1-sismos-auto[ ```r library(rvest) # descargar datos de paginas web *url <- "https://www.sismologia.cl/sismicidad/catalogo/2022/07/20220721.html" ``` ] .panel2-sismos-auto[ ] --- count: false ## Antes, unos datos .panel1-sismos-auto[ ```r library(rvest) # descargar datos de paginas web url <- "https://www.sismologia.cl/sismicidad/catalogo/2022/07/20220721.html" *read_html(url) ``` ] .panel2-sismos-auto[ ``` ## {html_document} ## <html lang="en"> ## [1] <head>\n<meta http-equiv="Content-Type" content="text/html; charset=UTF-8 ... ## [2] <body>\n <div class="main-container">\n <header><div class="inf"> ... ``` ] --- count: false ## Antes, unos datos .panel1-sismos-auto[ ```r library(rvest) # descargar datos de paginas web url <- "https://www.sismologia.cl/sismicidad/catalogo/2022/07/20220721.html" read_html(url) |> * html_table() ``` ] .panel2-sismos-auto[ ``` ## [[1]] ## # A tibble: 1 × 6 ## X1 X2 X3 X4 X5 X6 ## <lgl> <lgl> <lgl> <lgl> <lgl> <lgl> ## 1 NA NA NA NA NA NA ## ## [[2]] ## # A tibble: 11 × 5 ## `Fecha Local / Lugar` Fecha…¹ Latit…² Profu…³ Magni…⁴ ## <chr> <chr> <chr> <chr> <chr> ## 1 2022-07-21 18:36:3864 km al NO de Valparaíso 2022-0… -32.63… 28 km 3.9 Ml ## 2 2022-07-21 17:56:3118 km al SE de Quillota 2022-0… -33.02… 63 km 2.7 Ml ## 3 2022-07-21 12:43:2362 km al S de Socaire 2022-0… -24.12… 264 km 2.8 Ml ## 4 2022-07-21 12:29:3153 km al SE de Socaire 2022-0… -23.90… 264 km 2.6 Ml ## 5 2022-07-21 10:06:0364 km al SO de Ollagüe 2022-0… -21.74… 133 km 3.5 Ml ## 6 2022-07-21 09:49:0626 km al NE de Sierra Gor… 2022-0… -22.72… 60 km 3.2 Ml ## 7 2022-07-21 05:57:0717 km al SO de Las Cabras 2022-0… -34.39… 54 km 3.0 Ml ## 8 2022-07-21 05:27:5667 km al SE de Socaire 2022-0… -24.11… 241 km 3.7 Ml ## 9 2022-07-21 04:35:47216 km al SO de Melinka 2022-0… -45.15… 33 km 3.5 Ml ## 10 2022-07-20 22:48:5254 km al NE de San Pedro … 2022-0… -22.46… 197 km 3.1 Ml ## 11 2022-07-20 21:17:0326 km al S de Calama 2022-0… -22.69… 108 km 3.4 Ml ## # … with abbreviated variable names ¹`Fecha UTC`, ²`Latitud / Longitud`, ## # ³Profundidad, ⁴`Magnitud (2)` ``` ] --- count: false ## Antes, unos datos .panel1-sismos-auto[ ```r library(rvest) # descargar datos de paginas web url <- "https://www.sismologia.cl/sismicidad/catalogo/2022/07/20220721.html" read_html(url) |> html_table() |> * dplyr::nth(2) ``` ] .panel2-sismos-auto[ ``` ## # A tibble: 11 × 5 ## `Fecha Local / Lugar` Fecha…¹ Latit…² Profu…³ Magni…⁴ ## <chr> <chr> <chr> <chr> <chr> ## 1 2022-07-21 18:36:3864 km al NO de Valparaíso 2022-0… -32.63… 28 km 3.9 Ml ## 2 2022-07-21 17:56:3118 km al SE de Quillota 2022-0… -33.02… 63 km 2.7 Ml ## 3 2022-07-21 12:43:2362 km al S de Socaire 2022-0… -24.12… 264 km 2.8 Ml ## 4 2022-07-21 12:29:3153 km al SE de Socaire 2022-0… -23.90… 264 km 2.6 Ml ## 5 2022-07-21 10:06:0364 km al SO de Ollagüe 2022-0… -21.74… 133 km 3.5 Ml ## 6 2022-07-21 09:49:0626 km al NE de Sierra Gor… 2022-0… -22.72… 60 km 3.2 Ml ## 7 2022-07-21 05:57:0717 km al SO de Las Cabras 2022-0… -34.39… 54 km 3.0 Ml ## 8 2022-07-21 05:27:5667 km al SE de Socaire 2022-0… -24.11… 241 km 3.7 Ml ## 9 2022-07-21 04:35:47216 km al SO de Melinka 2022-0… -45.15… 33 km 3.5 Ml ## 10 2022-07-20 22:48:5254 km al NE de San Pedro … 2022-0… -22.46… 197 km 3.1 Ml ## 11 2022-07-20 21:17:0326 km al S de Calama 2022-0… -22.69… 108 km 3.4 Ml ## # … with abbreviated variable names ¹`Fecha UTC`, ²`Latitud / Longitud`, ## # ³Profundidad, ⁴`Magnitud (2)` ``` ] --- count: false ## Antes, unos datos .panel1-sismos-auto[ ```r library(rvest) # descargar datos de paginas web url <- "https://www.sismologia.cl/sismicidad/catalogo/2022/07/20220721.html" read_html(url) |> html_table() |> dplyr::nth(2) |> * janitor::clean_names() ``` ] .panel2-sismos-auto[ ``` ## # A tibble: 11 × 5 ## fecha_local_lugar fecha…¹ latit…² profu…³ magni…⁴ ## <chr> <chr> <chr> <chr> <chr> ## 1 2022-07-21 18:36:3864 km al NO de Valparaíso 2022-0… -32.63… 28 km 3.9 Ml ## 2 2022-07-21 17:56:3118 km al SE de Quillota 2022-0… -33.02… 63 km 2.7 Ml ## 3 2022-07-21 12:43:2362 km al S de Socaire 2022-0… -24.12… 264 km 2.8 Ml ## 4 2022-07-21 12:29:3153 km al SE de Socaire 2022-0… -23.90… 264 km 2.6 Ml ## 5 2022-07-21 10:06:0364 km al SO de Ollagüe 2022-0… -21.74… 133 km 3.5 Ml ## 6 2022-07-21 09:49:0626 km al NE de Sierra Gor… 2022-0… -22.72… 60 km 3.2 Ml ## 7 2022-07-21 05:57:0717 km al SO de Las Cabras 2022-0… -34.39… 54 km 3.0 Ml ## 8 2022-07-21 05:27:5667 km al SE de Socaire 2022-0… -24.11… 241 km 3.7 Ml ## 9 2022-07-21 04:35:47216 km al SO de Melinka 2022-0… -45.15… 33 km 3.5 Ml ## 10 2022-07-20 22:48:5254 km al NE de San Pedro … 2022-0… -22.46… 197 km 3.1 Ml ## 11 2022-07-20 21:17:0326 km al S de Calama 2022-0… -22.69… 108 km 3.4 Ml ## # … with abbreviated variable names ¹fecha_utc, ²latitud_longitud, ## # ³profundidad, ⁴magnitud_2 ``` ] --- count: false ## Antes, unos datos .panel1-sismos-auto[ ```r library(rvest) # descargar datos de paginas web url <- "https://www.sismologia.cl/sismicidad/catalogo/2022/07/20220721.html" read_html(url) |> html_table() |> dplyr::nth(2) |> janitor::clean_names() |> * tidyr::separate( * latitud_longitud, * into = c("latitud", "longitud"), * sep = " ", convert = TRUE * ) ``` ] .panel2-sismos-auto[ ``` ## # A tibble: 11 × 6 ## fecha_local_lugar fecha…¹ latitud longi…² profu…³ magni…⁴ ## <chr> <chr> <dbl> <dbl> <chr> <chr> ## 1 2022-07-21 18:36:3864 km al NO de Va… 2022-0… -32.6 -72.1 28 km 3.9 Ml ## 2 2022-07-21 17:56:3118 km al SE de Qu… 2022-0… -33.0 -71.1 63 km 2.7 Ml ## 3 2022-07-21 12:43:2362 km al S de Soc… 2022-0… -24.1 -67.7 264 km 2.8 Ml ## 4 2022-07-21 12:29:3153 km al SE de So… 2022-0… -23.9 -67.5 264 km 2.6 Ml ## 5 2022-07-21 10:06:0364 km al SO de Ol… 2022-0… -21.7 -68.5 133 km 3.5 Ml ## 6 2022-07-21 09:49:0626 km al NE de Si… 2022-0… -22.7 -69.2 60 km 3.2 Ml ## 7 2022-07-21 05:57:0717 km al SO de La… 2022-0… -34.4 -71.4 54 km 3.0 Ml ## 8 2022-07-21 05:27:5667 km al SE de So… 2022-0… -24.1 -67.6 241 km 3.7 Ml ## 9 2022-07-21 04:35:47216 km al SO de M… 2022-0… -45.2 -75.8 33 km 3.5 Ml ## 10 2022-07-20 22:48:5254 km al NE de Sa… 2022-0… -22.5 -68.0 197 km 3.1 Ml ## 11 2022-07-20 21:17:0326 km al S de Cal… 2022-0… -22.7 -68.8 108 km 3.4 Ml ## # … with abbreviated variable names ¹fecha_utc, ²longitud, ³profundidad, ## # ⁴magnitud_2 ``` ] --- count: false ## Antes, unos datos .panel1-sismos-auto[ ```r library(rvest) # descargar datos de paginas web url <- "https://www.sismologia.cl/sismicidad/catalogo/2022/07/20220721.html" read_html(url) |> html_table() |> dplyr::nth(2) |> janitor::clean_names() |> tidyr::separate( latitud_longitud, into = c("latitud", "longitud"), sep = " ", convert = TRUE ) *datos <- read_html(url) ``` ] .panel2-sismos-auto[ ``` ## # A tibble: 11 × 6 ## fecha_local_lugar fecha…¹ latitud longi…² profu…³ magni…⁴ ## <chr> <chr> <dbl> <dbl> <chr> <chr> ## 1 2022-07-21 18:36:3864 km al NO de Va… 2022-0… -32.6 -72.1 28 km 3.9 Ml ## 2 2022-07-21 17:56:3118 km al SE de Qu… 2022-0… -33.0 -71.1 63 km 2.7 Ml ## 3 2022-07-21 12:43:2362 km al S de Soc… 2022-0… -24.1 -67.7 264 km 2.8 Ml ## 4 2022-07-21 12:29:3153 km al SE de So… 2022-0… -23.9 -67.5 264 km 2.6 Ml ## 5 2022-07-21 10:06:0364 km al SO de Ol… 2022-0… -21.7 -68.5 133 km 3.5 Ml ## 6 2022-07-21 09:49:0626 km al NE de Si… 2022-0… -22.7 -69.2 60 km 3.2 Ml ## 7 2022-07-21 05:57:0717 km al SO de La… 2022-0… -34.4 -71.4 54 km 3.0 Ml ## 8 2022-07-21 05:27:5667 km al SE de So… 2022-0… -24.1 -67.6 241 km 3.7 Ml ## 9 2022-07-21 04:35:47216 km al SO de M… 2022-0… -45.2 -75.8 33 km 3.5 Ml ## 10 2022-07-20 22:48:5254 km al NE de Sa… 2022-0… -22.5 -68.0 197 km 3.1 Ml ## 11 2022-07-20 21:17:0326 km al S de Cal… 2022-0… -22.7 -68.8 108 km 3.4 Ml ## # … with abbreviated variable names ¹fecha_utc, ²longitud, ³profundidad, ## # ⁴magnitud_2 ``` ] --- count: false ## Antes, unos datos .panel1-sismos-auto[ ```r library(rvest) # descargar datos de paginas web url <- "https://www.sismologia.cl/sismicidad/catalogo/2022/07/20220721.html" read_html(url) |> html_table() |> dplyr::nth(2) |> janitor::clean_names() |> tidyr::separate( latitud_longitud, into = c("latitud", "longitud"), sep = " ", convert = TRUE ) datos <- read_html(url) |> * html_table() ``` ] .panel2-sismos-auto[ ``` ## # A tibble: 11 × 6 ## fecha_local_lugar fecha…¹ latitud longi…² profu…³ magni…⁴ ## <chr> <chr> <dbl> <dbl> <chr> <chr> ## 1 2022-07-21 18:36:3864 km al NO de Va… 2022-0… -32.6 -72.1 28 km 3.9 Ml ## 2 2022-07-21 17:56:3118 km al SE de Qu… 2022-0… -33.0 -71.1 63 km 2.7 Ml ## 3 2022-07-21 12:43:2362 km al S de Soc… 2022-0… -24.1 -67.7 264 km 2.8 Ml ## 4 2022-07-21 12:29:3153 km al SE de So… 2022-0… -23.9 -67.5 264 km 2.6 Ml ## 5 2022-07-21 10:06:0364 km al SO de Ol… 2022-0… -21.7 -68.5 133 km 3.5 Ml ## 6 2022-07-21 09:49:0626 km al NE de Si… 2022-0… -22.7 -69.2 60 km 3.2 Ml ## 7 2022-07-21 05:57:0717 km al SO de La… 2022-0… -34.4 -71.4 54 km 3.0 Ml ## 8 2022-07-21 05:27:5667 km al SE de So… 2022-0… -24.1 -67.6 241 km 3.7 Ml ## 9 2022-07-21 04:35:47216 km al SO de M… 2022-0… -45.2 -75.8 33 km 3.5 Ml ## 10 2022-07-20 22:48:5254 km al NE de Sa… 2022-0… -22.5 -68.0 197 km 3.1 Ml ## 11 2022-07-20 21:17:0326 km al S de Cal… 2022-0… -22.7 -68.8 108 km 3.4 Ml ## # … with abbreviated variable names ¹fecha_utc, ²longitud, ³profundidad, ## # ⁴magnitud_2 ``` ] --- count: false ## Antes, unos datos .panel1-sismos-auto[ ```r library(rvest) # descargar datos de paginas web url <- "https://www.sismologia.cl/sismicidad/catalogo/2022/07/20220721.html" read_html(url) |> html_table() |> dplyr::nth(2) |> janitor::clean_names() |> tidyr::separate( latitud_longitud, into = c("latitud", "longitud"), sep = " ", convert = TRUE ) datos <- read_html(url) |> html_table() |> * dplyr::nth(2) ``` ] .panel2-sismos-auto[ ``` ## # A tibble: 11 × 6 ## fecha_local_lugar fecha…¹ latitud longi…² profu…³ magni…⁴ ## <chr> <chr> <dbl> <dbl> <chr> <chr> ## 1 2022-07-21 18:36:3864 km al NO de Va… 2022-0… -32.6 -72.1 28 km 3.9 Ml ## 2 2022-07-21 17:56:3118 km al SE de Qu… 2022-0… -33.0 -71.1 63 km 2.7 Ml ## 3 2022-07-21 12:43:2362 km al S de Soc… 2022-0… -24.1 -67.7 264 km 2.8 Ml ## 4 2022-07-21 12:29:3153 km al SE de So… 2022-0… -23.9 -67.5 264 km 2.6 Ml ## 5 2022-07-21 10:06:0364 km al SO de Ol… 2022-0… -21.7 -68.5 133 km 3.5 Ml ## 6 2022-07-21 09:49:0626 km al NE de Si… 2022-0… -22.7 -69.2 60 km 3.2 Ml ## 7 2022-07-21 05:57:0717 km al SO de La… 2022-0… -34.4 -71.4 54 km 3.0 Ml ## 8 2022-07-21 05:27:5667 km al SE de So… 2022-0… -24.1 -67.6 241 km 3.7 Ml ## 9 2022-07-21 04:35:47216 km al SO de M… 2022-0… -45.2 -75.8 33 km 3.5 Ml ## 10 2022-07-20 22:48:5254 km al NE de Sa… 2022-0… -22.5 -68.0 197 km 3.1 Ml ## 11 2022-07-20 21:17:0326 km al S de Cal… 2022-0… -22.7 -68.8 108 km 3.4 Ml ## # … with abbreviated variable names ¹fecha_utc, ²longitud, ³profundidad, ## # ⁴magnitud_2 ``` ] --- count: false ## Antes, unos datos .panel1-sismos-auto[ ```r library(rvest) # descargar datos de paginas web url <- "https://www.sismologia.cl/sismicidad/catalogo/2022/07/20220721.html" read_html(url) |> html_table() |> dplyr::nth(2) |> janitor::clean_names() |> tidyr::separate( latitud_longitud, into = c("latitud", "longitud"), sep = " ", convert = TRUE ) datos <- read_html(url) |> html_table() |> dplyr::nth(2) |> * janitor::clean_names() ``` ] .panel2-sismos-auto[ ``` ## # A tibble: 11 × 6 ## fecha_local_lugar fecha…¹ latitud longi…² profu…³ magni…⁴ ## <chr> <chr> <dbl> <dbl> <chr> <chr> ## 1 2022-07-21 18:36:3864 km al NO de Va… 2022-0… -32.6 -72.1 28 km 3.9 Ml ## 2 2022-07-21 17:56:3118 km al SE de Qu… 2022-0… -33.0 -71.1 63 km 2.7 Ml ## 3 2022-07-21 12:43:2362 km al S de Soc… 2022-0… -24.1 -67.7 264 km 2.8 Ml ## 4 2022-07-21 12:29:3153 km al SE de So… 2022-0… -23.9 -67.5 264 km 2.6 Ml ## 5 2022-07-21 10:06:0364 km al SO de Ol… 2022-0… -21.7 -68.5 133 km 3.5 Ml ## 6 2022-07-21 09:49:0626 km al NE de Si… 2022-0… -22.7 -69.2 60 km 3.2 Ml ## 7 2022-07-21 05:57:0717 km al SO de La… 2022-0… -34.4 -71.4 54 km 3.0 Ml ## 8 2022-07-21 05:27:5667 km al SE de So… 2022-0… -24.1 -67.6 241 km 3.7 Ml ## 9 2022-07-21 04:35:47216 km al SO de M… 2022-0… -45.2 -75.8 33 km 3.5 Ml ## 10 2022-07-20 22:48:5254 km al NE de Sa… 2022-0… -22.5 -68.0 197 km 3.1 Ml ## 11 2022-07-20 21:17:0326 km al S de Cal… 2022-0… -22.7 -68.8 108 km 3.4 Ml ## # … with abbreviated variable names ¹fecha_utc, ²longitud, ³profundidad, ## # ⁴magnitud_2 ``` ] --- count: false ## Antes, unos datos .panel1-sismos-auto[ ```r library(rvest) # descargar datos de paginas web url <- "https://www.sismologia.cl/sismicidad/catalogo/2022/07/20220721.html" read_html(url) |> html_table() |> dplyr::nth(2) |> janitor::clean_names() |> tidyr::separate( latitud_longitud, into = c("latitud", "longitud"), sep = " ", convert = TRUE ) datos <- read_html(url) |> html_table() |> dplyr::nth(2) |> janitor::clean_names() |> * tidyr::separate( * latitud_longitud, * into = c("latitud", "longitud"), * sep = " ", convert = TRUE * ) ``` ] .panel2-sismos-auto[ ``` ## # A tibble: 11 × 6 ## fecha_local_lugar fecha…¹ latitud longi…² profu…³ magni…⁴ ## <chr> <chr> <dbl> <dbl> <chr> <chr> ## 1 2022-07-21 18:36:3864 km al NO de Va… 2022-0… -32.6 -72.1 28 km 3.9 Ml ## 2 2022-07-21 17:56:3118 km al SE de Qu… 2022-0… -33.0 -71.1 63 km 2.7 Ml ## 3 2022-07-21 12:43:2362 km al S de Soc… 2022-0… -24.1 -67.7 264 km 2.8 Ml ## 4 2022-07-21 12:29:3153 km al SE de So… 2022-0… -23.9 -67.5 264 km 2.6 Ml ## 5 2022-07-21 10:06:0364 km al SO de Ol… 2022-0… -21.7 -68.5 133 km 3.5 Ml ## 6 2022-07-21 09:49:0626 km al NE de Si… 2022-0… -22.7 -69.2 60 km 3.2 Ml ## 7 2022-07-21 05:57:0717 km al SO de La… 2022-0… -34.4 -71.4 54 km 3.0 Ml ## 8 2022-07-21 05:27:5667 km al SE de So… 2022-0… -24.1 -67.6 241 km 3.7 Ml ## 9 2022-07-21 04:35:47216 km al SO de M… 2022-0… -45.2 -75.8 33 km 3.5 Ml ## 10 2022-07-20 22:48:5254 km al NE de Sa… 2022-0… -22.5 -68.0 197 km 3.1 Ml ## 11 2022-07-20 21:17:0326 km al S de Cal… 2022-0… -22.7 -68.8 108 km 3.4 Ml ## # … with abbreviated variable names ¹fecha_utc, ²longitud, ³profundidad, ## # ⁴magnitud_2 ``` ] <style> .panel1-sismos-auto { color: black; width: 32.6666666666667%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-sismos-auto { color: black; width: 65.3333333333333%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-sismos-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- count: false ## {DT} .panel1-dt-auto[ ```r *library(DT) ``` ] .panel2-dt-auto[ ] --- count: false ## {DT} .panel1-dt-auto[ ```r library(DT) *datatable(datos) ``` ] .panel2-dt-auto[
] <style> .panel1-dt-auto { color: black; width: 19.6%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-dt-auto { color: black; width: 78.4%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-dt-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- count: false ## {leaflet} .panel1-leaflet-auto[ ```r *library(leaflet) ``` ] .panel2-leaflet-auto[ ] --- count: false ## {leaflet} .panel1-leaflet-auto[ ```r library(leaflet) *leaflet(datos) ``` ] .panel2-leaflet-auto[
] --- count: false ## {leaflet} .panel1-leaflet-auto[ ```r library(leaflet) leaflet(datos) |> * addTiles() ``` ] .panel2-leaflet-auto[
] --- count: false ## {leaflet} .panel1-leaflet-auto[ ```r library(leaflet) leaflet(datos) |> addTiles() |> * addMarkers( * lng = ~longitud, * lat = ~latitud, * popup = ~as.character(magnitud_2), * label = ~as.character(`fecha_local_lugar`) * ) ``` ] .panel2-leaflet-auto[
] --- count: false ## {leaflet} .panel1-leaflet-auto[ ```r library(leaflet) leaflet(datos) |> addTiles() |> addMarkers( lng = ~longitud, lat = ~latitud, popup = ~as.character(magnitud_2), label = ~as.character(`fecha_local_lugar`) ) |> * addProviderTiles("Esri.WorldImagery") ``` ] .panel2-leaflet-auto[
] <style> .panel1-leaflet-auto { color: black; width: 38.6060606060606%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-leaflet-auto { color: black; width: 59.3939393939394%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-leaflet-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- ## HTMLWidgets en reporte/dashboard <br> La integración es inmediata **siempre y cuando** el output sea html o dashboard (que es también html) y slides (que no sea pdf/ppt).