在 R 中使用 For 循环从 excel 个文件创建嵌套列表
Create Nested Lists from excel files using For loop in R
我有几个 excel 个文件 (*.xlsx),每个文件都有很多页。我想从每个文件创建一个嵌套列表。尽管我可以使用以下代码为每个文件单独执行此操作。
g1 <- file1 %>%
excel_sheets() %>%
set_names() %>%
map(read_excel, path = file1)
但是,如果我必须为 5 个 excel 文件创建一些 5 个嵌套列表 g1, g2, g3, g4, g5
。然后我必须为每个变量编写上面的代码 5 次。我们可以使用 for loop
遍历 list.files
以减少行数吗?
我需要嵌套列表,因为我会在稍后阶段合并它们。
我做了如下粗略的尝试:
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])
}
但这不起作用。
也许会有用
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))
我有几个 excel 个文件 (*.xlsx),每个文件都有很多页。我想从每个文件创建一个嵌套列表。尽管我可以使用以下代码为每个文件单独执行此操作。
g1 <- file1 %>%
excel_sheets() %>%
set_names() %>%
map(read_excel, path = file1)
但是,如果我必须为 5 个 excel 文件创建一些 5 个嵌套列表 g1, g2, g3, g4, g5
。然后我必须为每个变量编写上面的代码 5 次。我们可以使用 for loop
遍历 list.files
以减少行数吗?
我需要嵌套列表,因为我会在稍后阶段合并它们。
我做了如下粗略的尝试:
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])
}
但这不起作用。
也许会有用
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))