我有多个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日创建。