【问题标题】:Writing a new column in all excel files (and all sheets in an excel file) in a folder using R使用R在文件夹中的所有excel文件(以及excel文件中的所有工作表)中写入一个新列
【发布时间】:2021-05-21 11:33:24
【问题描述】:

所以,我在一个文件夹中有许多 excel 文件,每个文件都有多个工作表。如果 excel 文件的名称是“xyz”,我希望每个 excel 文件的每张表都包含一个“new_column”,这样新列的每一行都将包含 excel 文件名(在本例中为“xyz”)。

有没有直接的方法可以做到这一点?我宁愿直接更改文件夹中的文件,而不在 rstudio 中创建新的数据框。

谢谢。

【问题讨论】:

    标签: r excel


    【解决方案1】:

    你可以使用双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)
    })
    

    【讨论】:

    • 谢谢。但我认为文件名向量正在制造一些问题。我目录中的第一个示例 excel 文件名称为“excel 1”,我收到以下错误。 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 &lt;- 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, :
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多