【发布时间】:2021-05-21 11:33:24
【问题描述】:
所以,我在一个文件夹中有许多 excel 文件,每个文件都有多个工作表。如果 excel 文件的名称是“xyz”,我希望每个 excel 文件的每张表都包含一个“new_column”,这样新列的每一行都将包含 excel 文件名(在本例中为“xyz”)。
有没有直接的方法可以做到这一点?我宁愿直接更改文件夹中的文件,而不在 rstudio 中创建新的数据框。
谢谢。
【问题讨论】:
所以,我在一个文件夹中有许多 excel 文件,每个文件都有多个工作表。如果 excel 文件的名称是“xyz”,我希望每个 excel 文件的每张表都包含一个“new_column”,这样新列的每一行都将包含 excel 文件名(在本例中为“xyz”)。
有没有直接的方法可以做到这一点?我宁愿直接更改文件夹中的文件,而不在 rstudio 中创建新的数据框。
谢谢。
【问题讨论】:
你可以使用双lapply -
library(readxl)
library(writexl)
#Get a vector of xlsx filenames
filenames <- list.files(pattern = '.xlsx', full.names = TRUE)
lapply(filenames, function(x) {
#Read the sheet names
sheetname <- excel_sheets(x)
#For each sheet read the data and create list of dataframe
lapply(sheetname, function(y) {
cbind(read_xlsx(x, y), filename = x)
}) -> res
#Assign names to the list
names(res) <- sheetname
#Write the data back
write_xlsx(res, x)
})
【讨论】:
Error: Evaluation error: zip file './~$excel 1.xlsx' cannot be opened.文件名向量是这样的(只包含2个名字):[1] "./~$excel 1.xlsx" "./~$excel 2.xlsx" "./excel 1.xlsx" "./excel 2.xlsx"
filenames <- list.files(pattern = "[^~]\\.xlsx", full.names = TRUE)
Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 0, 1 In addition: Warning message: In read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, :