读取多个 xlsx 文件,每个文件都有多个工作表 - purrr

标签 r purrr readxl

我有多个 Excel 文件,每个文件都有不同的工作表。我尝试使用 readxl 和 map 将其导入到 R 中。但是,我只能使用 for 循环来完成此操作。下面的代码工作正常,但我想知道是否有一个聪明的方法来做到这一点。我一直认为我可以用 map2 来完成它,但我错过了一些东西。

library(tidyverse)
library(readxl)
library(writexl)

### As a first step, I get all the files from my project folder and create an empty list for looping purposes

files <- list.files(pattern = ".xlsx")
data_xlsx <- list()

### I then use seq_along in all the files and map_df to read the each excel file

for (i in seq_along(files)) {
data_xlsx[[i]] <- files[i] %>% 
  excel_sheets() %>% 
  set_names() %>% 
  map_df(
    ~ read_xlsx(path = files[i], sheet = .x, range = "H3"),
    .id = "sheet")
}

# I use the code below to get the files name into the list

data_xlsx <- set_names(data_xlsx, files)

# This final code is just to transform the list into a data frame with a column with the name of the files

data_xlsx_df <- map2_df(data_xlsx, files, ~update_list(.x, file = .y))

reprex package于2018年7月1日创建(v0.2.0)。

最佳答案

您可以使用嵌套的map_df调用来替换for循环。据我所知 map2 只能对两个长度为 n 的列表进行操作并返回一个长度为 n 的列表,我不认为这是一种从长度为 nm 的两个列表生成长度为 n * m 列表的方法。

files <- list.files(pattern = ".xlsx")

data_xlsx_df <- map_df(set_names(files), function(file) {
  file %>% 
    excel_sheets() %>% 
    set_names() %>% 
    map_df(
      ~ read_xlsx(path = file, sheet = .x, range = "H3"),
      .id = "sheet")
}, .id = "file")

关于读取多个 xlsx 文件,每个文件都有多个工作表 - purrr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51120287/

相关文章:

r - 使用 purrr 方式将列出的列转换为 R 中的字符串

r - 使用 read_excel "Error: std::bad_alloc"的错误信息

RStudio read.xl 工作目录错误

r - 更改箱线图的布局并为其添加标签

R:计算至少抽到 1 个红色弹珠的概率

r - 如何在 purrr 中的多个数据集上拟合多个模型?

r- 使用 purrr::map 时存储警告消息而不丢弃结果

使用 read_excel 自动删除列名中的所有空格

r - R Hive Thrift客户

r - 如何四舍五入矩阵中的所有值?