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

问题描述 投票:1回答:1

我有多个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-07-01(v0.2.0)。

r purrr readxl
1个回答
5
投票

您可以使用嵌套的map_df调用来替换for循环。据我所知,map2只能在两个长度为n的列表上运行并返回长度为n的列表,我认为这不是从两个长度为n * mn的列表生成长度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")
© www.soinside.com 2019 - 2024. All rights reserved.