I have several excel files (*.xlsx) and each file has many sheets. I want to create a nested list from each file. Although I can do it individually for each file by using the following code.
g1 <- file1 %>%
excel_sheets() %>%
set_names() %>%
map(read_excel, path = file1)
However, if I have to create some 5 nested lists g1, g2, g3, g4, g5
for 5 excel files. Then I have to write the above code 5 times for each variable. Can we use for loop
to iterate over list.files
so that number of lines be reduced.
I need nested lists because I would merge them at a later stage.
I made a crude attempt as follows:
files <- list.files(pattern = "*.xlsx")
for (i in 1:length(files)){
"g"[i] <- files[i] %>%
excel_sheets() %>%
set_names() %>%
map(read_excel, path = files[i])
}
But this does not work.
CodePudding user response:
perhaps it will be useful
library(tidyverse)
library(readxl)
path <- here::here("source", "xlsx")
list_files <- fs::dir_ls(path)
tibble(files = list_files) %>%
mutate(sheets = map(files, excel_sheets)) %>%
unnest(sheets) %>%
mutate(data = map2(files, sheets, read_xlsx))