簡體   English   中英

如何將數據框的名稱傳遞給Excel工作表(使用xlsx包)

[英]How to pass the name of a data frame to an Excel worksheet (using xlsx package)

我正在嘗試使用lapply來瀏覽數據幀列表並對每個數據幀執行自定義函數。 在函數中,我試圖根據數據集的名稱命名工作表(使用xlsx)。 這可能嗎? 見例子:

myList <- list(DataFrame1, DataFrame2, DataFrame3, DataFrame4)

require(xlsx)
export <- createWorkbook()

lapply(myList,
       ExcelExport <- function(dataset) {

nameDF <- deparse(substitute(dataset))

# Use another function and store the output               
DF <- as.data.frame(function2(dataset)) 
# Here is where I'm having trouble naming the worksheet according to the name of the Dataframe:               
wksht <- createSheet(wb=export, sheetName = paste("Dataset is ", nameDF, sep = ""))  
               addDataFrame(x=DF, sheet = wksht)


)
# Save it to an excel file (either existing or new) under a given name
saveWorkbook(export, "Export1.xlsx")

我從獲取數據框的名稱中找到了deparse(substitute()) ,但lapply似乎是將我的數據框重命名為X[[i]] ,然后為“[” X[[i]]拋出無效字符的錯誤

這是編輯后的代碼,允許您訪問列表節點的名稱。 請在發布前檢查您的代碼,它包含一些含糊之處。

myList <- list(DataFrame1 = data.frame(matrix(rnorm(100), 10, 10)), 
               DataFrame2 = data.frame(matrix(rnorm(100), 10, 10)), 
               DataFrame3 = data.frame(matrix(rnorm(100), 10, 10)), 
               DataFrame4 = data.frame(matrix(rnorm(100), 10, 10)))

require(xlsx)
export <- createWorkbook()

lapply(seq_along(myList), function(i) {
  ExcelExport <- function1(myList[[i]]) # Your code was incomplete here
  # You don't have object 'ExcelExport' anywhere esle in your code
  # so this step seems useless...

  # Now you have a full access to myList inside lapply 
  nameDF <- names(myList)[i]

  # Use another function and store the output               
  DF <- as.data.frame(function2(myList[[i]])) 

  wksht <- createSheet(wb=export, sheetName = paste("Dataset is ", nameDF, sep = ""))  
  addDataFrame(x=DF, sheet = wksht) # Btw, object 'wksht' is not defined in your code

})
# Save it to an excel file (either existing or new) under a given name
saveWorkbook(export, "Export1.xlsx")

暫無
暫無

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

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