我有多个 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))
创建于 2018-07-01代表包 http://reprex.tidyverse.org(v0.2.0)。
您可以使用嵌套map_df
调用来替换 for 循环。据我所知map2
只能对两个长度的列表进行操作n
并返回一个长度列表n
,我不认为这是生成长度的方法n * m
两个长度列表中的列表n
and 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")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)