簡體   English   中英

使用 R 在文件夾中的所有 excel 文件(以及 excel 文件中的所有工作表)中寫入新列

[英]Writing a new column in all excel files (and all sheets in an excel file) in a folder using R

所以,我在一個文件夾中有很多 excel 文件,每個文件都有多個工作表。 If the name of the excel file is 'xyz', I want each sheet of each excel file to contain a 'new_column' such that each row of the new column will contain the excel file name (in this example, '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)
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM