[英]Read one worksheet from multiple excel files using purrr and readxl and add field
Suppose I have two excel files named packs .xlsx and each contains multiple sheets.假设我有两个名为packs.xlsx的 excel 文件,每个文件都包含多个工作表。 I want to iteratively create a dataframe using only 1 sheet from each file, each named "summary".
我想迭代地创建一个 dataframe 只使用每个文件中的一张纸,每个文件都命名为“摘要”。 How can I go about this using Purrr and readxl while also adding a field which contains the filename?
我如何使用 Purrr 和 readxl go,同时添加一个包含文件名的字段?
I'm successful when I save the sheets as CSVs using the following code:当我使用以下代码将工作表另存为 CSV 时,我成功了:
filenames <- list.files(pattern="packs*.*csv")
dat <- map_dfr(filenames, read_xlsx, sheet = "summary") %>% glimpse()
How would I go about adding a field to show which file a given row came from?我 go 如何添加一个字段来显示给定行来自哪个文件? Thanks for any insight that can be offered!
感谢您提供的任何见解!
Supposing the two packs.xlsx files are in different subfolders:假设这两个 packs.xlsx 文件位于不同的子文件夹中:
library(readxl)
filenames <- list.files(pattern = "packs.xlsx", recursive = TRUE)
df <- lapply(filenames, function(fn) {
# get the sheet detail
xl <- read_excel(fn, sheet = "summary")
# add the filename as a field
xl$filename <- fn
# function return
xl
})
# if both summary sheets have the same format, you can combine them into one
fin <- do.call(rbind, df)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.