class: center, middle .linea-superior[] .linea-inferior[] <img src="imagenes/logo_super_portada.png" width="180" /> # Curso Capacitación en R ## Sesión 5 ## Bases de datos 3 (importación y herramientas de utilidad) ### Junio 2025 --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Entendiendo directorios -- Para mantener un trabajo ordenado en cuanto a bases a cargar y exportar, es necesario saber correctamente en qué lugar nos encontramos. Debido a esto, se hace relevante conocer la forma en que se estructuran las carpetas y como R puede interactuar con ellas. -- ``` r getwd() # imprime el lugar donde nos encontramos en este momento ``` ``` ## [1] "/Users/noliverop/Desktop/Curso_R_SIS/Curso-R-SIS" ``` Para cambiar de lugar (cambiar de directorio) utilizamos la función `setwd()`. ``` r # "D:\OneDrive - superdesalud.gob.cl\Desktop\Clases R\Sesion_1" en windows # "D:/OneDrive - superdesalud.gob.cl/Desktop/Clases R/Sesion_1" setwd("D:/OneDrive - superdesalud.gob.cl/Desktop/Clases R/Sesion_1") ``` --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Entendiendo directorios También existen funciones que nos permiten ver la lista de directorios y/o archivos en una determinada ubicación. ``` r list.dirs(recursive = FALSE) ``` ``` ## [1] "./.git" "./.Rproj.user" ## [3] "./imagenes" "./sesion_1_presentacion_files" ## [5] "./sesion_2_presentacion_files" "./sesion_3_presentacion_files" ## [7] "./sesion_4_presentacion_files" "./sesion_5_presentacion_files" ## [9] "./tarea_1_files" "./tarea_1_solucion_files" ## [11] "./tarea_2_enunciado_files" "./tarea_3_enunciado_files" ``` ``` r list.files(recursive = FALSE) ``` ``` ## [1] "creacion_ejemplos_y_graficos.R" "ej_csv.csv" ## [3] "ej_excel.xlsx" "imagenes" ## [5] "miniejercicio_sesion_2.R" "notas_tarea_1.html" ## [7] "notas_tarea_1.Rmd" "README.md" ## [9] "sesion_1_presentacion_files" "sesion_1_presentacion.html" ## [11] "sesion_1_presentacion.Rmd" "Sesion_1.Rproj" ## [13] "sesion_2_presentacion_files" "sesion_2_presentacion.html" ## [15] "sesion_2_presentacion.Rmd" "sesion_3_presentacion_files" ## [17] "sesion_3_presentacion.html" "sesion_3_presentacion.Rmd" ## [19] "sesion_4_presentacion_files" "sesion_4_presentacion.html" ## [21] "sesion_4_presentacion.Rmd" "sesion_5_presentacion_files" ## [23] "sesion_5_presentacion.html" "sesion_5_presentacion.Rmd" ## [25] "sesion2.Rmd" "tarea_1_files" ## [27] "tarea_1_solucion_files" "tarea_1_solucion.html" ## [29] "tarea_1_solucion.Rmd" "tarea_1.html" ## [31] "tarea_1.R" "tarea_1.Rmd" ## [33] "tarea_2_enunciado_files" "tarea_2_enunciado.html" ## [35] "tarea_2_enunciado.Rmd" "tarea_2_solucion.Rmd" ## [37] "tarea_3_enunciado_files" "tarea_3_enunciado.html" ## [39] "tarea_3_enunciado.Rmd" "tarea_4_enunciado.Rmd" ## [41] "xaringan-themer.css" ``` --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Entendiendo directorios Contemplar que las funciones entregan vectores. ``` r directorio <- list.dirs(recursive = FALSE) directorio[2] ``` ``` ## [1] "./.Rproj.user" ``` ``` r length(directorio) ``` ``` ## [1] 12 ``` --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Importando archivos Primero exploremos la forma gráfica y visual de importar archivos CVS. -- Archivo CSV: ``` r library(readr) ej_csv <- read_csv("ej_csv.csv", locale = locale(grouping_mark = "")) ej_csv ``` ``` ## # A tibble: 7 × 4 ## Letra `Número entero` `Número decimal v1` `Número decimal v2` ## <chr> <dbl> <chr> <dbl> ## 1 a 1 1,5 2.1 ## 2 b 2 2,5 2.2 ## 3 c 3 3,5 2.3 ## 4 d 4 4,5 2.4 ## 5 e 5 5,5 2.5 ## 6 f 6 <NA> 2.6 ## 7 g 7 7,5 2.7 ``` --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Importando archivos Ahora exploremos la forma gráfica y visual de importar archivos Excel. -- Archivo Excel: ``` r library(readxl) ej_excel <- read_excel("ej_excel.xlsx") ej_excel ``` ``` ## # A tibble: 7 × 4 ## Letra `Número entero` `Número decimal v1` `Número decimal v2` ## <chr> <dbl> <chr> <dbl> ## 1 a 1 1,5 2.1 ## 2 b 2 2,5 2.2 ## 3 c 3 3,5 2.3 ## 4 d 4 4,5 2.4 ## 5 e 5 5,5 2.5 ## 6 f 6 <NA> 2.6 ## 7 g 7 7,5 2.7 ``` --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Exportemos archivos Primero modifiquemos nuestro archivo CSV: ``` r library(dplyr) ej_csv <- ej_csv |> rename_with(tolower) ej_csv <- ej_csv |> rename_with(~gsub(" ", "_", .x, fixed = TRUE)) ej_csv ``` ``` ## # A tibble: 7 × 4 ## letra número_entero número_decimal_v1 número_decimal_v2 ## <chr> <dbl> <chr> <dbl> ## 1 a 1 1,5 2.1 ## 2 b 2 2,5 2.2 ## 3 c 3 3,5 2.3 ## 4 d 4 4,5 2.4 ## 5 e 5 5,5 2.5 ## 6 f 6 <NA> 2.6 ## 7 g 7 7,5 2.7 ``` --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Exportemos archivos Ahora exportamos un archivo con formato csv: ``` r write.table(ej_csv,"ej_csv_exp1.csv",dec = ",", sep = ";", row.names=FALSE) ``` -- ``` r write.table(ej_csv,"ej_csv_exp2.csv",dec = ".", sep = ";", row.names=FALSE) ``` -- En Excel cuando tengan problemas al cargar archivos csv utilicen la herramienta en datos -> Desde el texto/CSV. --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Exportemos archivos El paquete `readr` como vimos permite importar archivos excel pero no permite exportar en excel. Si necesitan exportar directamente a excel recomiento la librería `openxlsx2`. ``` r library(openxlsx2) ``` -- Cambiemos un poco nuestra base de excel. ``` r ej_excel <- ej_excel |> mutate(codigo = paste(Letra,`Número entero`,sep="-")) ej_excel ``` ``` ## # A tibble: 7 × 5 ## Letra `Número entero` `Número decimal v1` `Número decimal v2` codigo ## <chr> <dbl> <chr> <dbl> <chr> ## 1 a 1 1,5 2.1 a-1 ## 2 b 2 2,5 2.2 b-2 ## 3 c 3 3,5 2.3 c-3 ## 4 d 4 4,5 2.4 d-4 ## 5 e 5 5,5 2.5 e-5 ## 6 f 6 <NA> 2.6 f-6 ## 7 g 7 7,5 2.7 g-7 ``` --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Exportemos archivos ``` r write_xlsx(ej_excel, "ej_excel.xlsx") ``` -- ``` r write_xlsx(ej_excel, "ej_excel.xlsx", as_table = TRUE) ``` -- ``` r write_xlsx(ej_excel, "ej_excel.xlsx", font_name="Verdana") ``` -- A pesar de la comodidad que entregan las librerías para exportar en Excel, recomiendo fuertemente leer y escribir datos en formato **plano** como por ejemplo archivos CSV. --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Uniones de Bases de Datos <br/> <br/> .center[<img src="imagenes/union1.png" />] -- .center[<img src="imagenes/union2.png" />] --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Uniones de Bases de Datos <br/> <br/> .pull-left[<img src="imagenes/union3.png" />] -- .pull-right[<img src="imagenes/union4.png" />] --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Uniones de Bases de Datos <br/> <br/> .center[<img src="imagenes/union5.png" />] --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Uniones de Bases de Datos Diagrama de resumen: <br/> <br/> .center[<img src="imagenes/union6.png" />] --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Uniones de Bases de Datos Veamos algunos ejemplos: ``` r miembros_banda <- band_members instrumentos_banda <- band_instruments instrumentos2_banda <- band_instruments2 ``` -- ``` r inner_example1 <- miembros_banda |> inner_join(instrumentos_banda) ``` ``` ## Joining with `by = join_by(name)` ``` ``` r inner_example1 ``` ``` ## # A tibble: 2 × 3 ## name band plays ## <chr> <chr> <chr> ## 1 John Beatles guitar ## 2 Paul Beatles bass ``` --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Uniones de Bases de Datos Veamos algunos ejemplos: ``` r left_example1 <- miembros_banda |> left_join(instrumentos_banda) left_example1 ``` ``` ## # A tibble: 3 × 3 ## name band plays ## <chr> <chr> <chr> ## 1 Mick Stones <NA> ## 2 John Beatles guitar ## 3 Paul Beatles bass ``` -- ``` r right_example1 <- miembros_banda |> right_join(instrumentos_banda) right_example1 ``` ``` ## # A tibble: 3 × 3 ## name band plays ## <chr> <chr> <chr> ## 1 John Beatles guitar ## 2 Paul Beatles bass ## 3 Keith <NA> guitar ``` --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Uniones de Bases de Datos ``` r full_example1 <- miembros_banda |> full_join(instrumentos_banda) full_example1 ``` ``` ## # A tibble: 4 × 3 ## name band plays ## <chr> <chr> <chr> ## 1 Mick Stones <NA> ## 2 John Beatles guitar ## 3 Paul Beatles bass ## 4 Keith <NA> guitar ``` -- A pesar de los ejemplos anteriores que el lenguaje infiere correctamente qué llave utilizar para unir las bases, es recomendable siempre **explicitar** la llave utilizada. ``` r inner_example2 <- miembros_banda |> inner_join(instrumentos_banda, by = join_by(name)) inner_example2 ``` ``` ## # A tibble: 2 × 3 ## name band plays ## <chr> <chr> <chr> ## 1 John Beatles guitar ## 2 Paul Beatles bass ``` --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Uniones de Bases de Datos ``` r full_example2 <- miembros_banda |> full_join(instrumentos2_banda, by = join_by(name == artist)) full_example2 ``` ``` ## # A tibble: 4 × 3 ## name band plays ## <chr> <chr> <chr> ## 1 Mick Stones <NA> ## 2 John Beatles guitar ## 3 Paul Beatles bass ## 4 Keith <NA> guitar ``` --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Uniones de Bases de Datos Otros tipos de ejemplos: ``` r df1 <- tibble(x = 1:3) # recuerden que un tibble es un data frame df2 <- tibble(x = c(1, 1, 2), y = c("first", "second", "third")) df1 ``` ``` ## # A tibble: 3 × 1 ## x ## <int> ## 1 1 ## 2 2 ## 3 3 ``` ``` r df2 ``` ``` ## # A tibble: 3 × 2 ## x y ## <dbl> <chr> ## 1 1 first ## 2 1 second ## 3 2 third ``` --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Uniones de Bases de Datos ``` r df1_df_2_left <- df1 |> left_join(df2, by = join_by(x)) df1_df_2_left ``` ``` ## # A tibble: 4 × 2 ## x y ## <dbl> <chr> ## 1 1 first ## 2 1 second ## 3 2 third ## 4 3 <NA> ``` -- ``` r df3 <- tibble(x = c(1, 1, 1, 3)) df3 ``` ``` ## # A tibble: 4 × 1 ## x ## <dbl> ## 1 1 ## 2 1 ## 3 1 ## 4 3 ``` --- background-image: url("imagenes/background.png") background-size: contain; background-position: 50% 0% # Uniones de Bases de Datos ``` r df3_df2_left <- df3 |> left_join(df2, by = join_by(x)) ``` ``` ## Warning in left_join(df3, df2, by = join_by(x)): Detected an unexpected many-to-many relationship between `x` and `y`. ## ℹ Row 1 of `x` matches multiple rows in `y`. ## ℹ Row 1 of `y` matches multiple rows in `x`. ## ℹ If a many-to-many relationship is expected, set `relationship = ## "many-to-many"` to silence this warning. ``` ``` r df3_df2_left ``` ``` ## # A tibble: 7 × 2 ## x y ## <dbl> <chr> ## 1 1 first ## 2 1 second ## 3 1 first ## 4 1 second ## 5 1 first ## 6 1 second ## 7 3 <NA> ```