Created
December 10, 2025 01:23
-
-
Save bastianolea/5c896dab18924a9cc0346fd7570ee28b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # código para cargar los datos de todas las hojas de un archivo de Excel y unirlas en una sola tabla | |
| # crear datos falsos ---- | |
| library(purrr) | |
| library(dplyr) | |
| nombres_hojas <- paste("hoja", 1:20) | |
| # crear una lista con tablas de datos sintéticos | |
| datos_falsos <- map( # iterar por cada elemento | |
| set_names(nombres_hojas), # poner nombre a cada elemento | |
| ~{ | |
| n = sample(5:30, 1) # cantidad de filas al azar | |
| # datos al azar | |
| datos <- tibble(variable_a = sample(letters, n, replace = T), | |
| variable_b = rnorm(n), | |
| variable_c = rnorm(n), | |
| ) | |
| # que una de las tablas sea distinta | |
| if (.x == "hoja 13") { | |
| datos <- datos |> | |
| mutate(variable_c = sample(letters, n, replace = T)) | |
| } | |
| return(datos) | |
| } | |
| ) | |
| # guardar archivo | |
| writexl::write_xlsx(datos_falsos, "datos_falsos.xlsx") | |
| # leer y unir hojas de excel ---- | |
| library(readxl) | |
| # obtener nombres de las hojas | |
| nombres_hojas <- readxl::excel_sheets("datos_falsos.xlsx") | |
| datos <- map( | |
| nombres_hojas, # iterar por el nombre de cada hoja | |
| ~{ | |
| message(.x) # decir la hoja al leerla | |
| read_excel("datos_falsos.xlsx", sheet = .x) |> | |
| mutate(variable_c = as.numeric(variable_c)) |> | |
| mutate(hoja = .x) # agregar nombre de hoja como columna | |
| } | |
| ) | |
| datos_unidos <- list_rbind(datos) | |
| datos_unidos | |
| # guardar como excel | |
| writexl::write_xlsx(datos_unidos, "datos_unidos.xlsx") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment