读取多个包含多个工作表的xlsx文件 - purrr

3

我有多个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 (v0.2.0)在2018年7月1日创建。

1个回答

10

您可以使用嵌套的 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")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接