2015-05-13 78 views
3

我正在嘗試使用lapply來檢查數據框的列表併爲每個數據框執行自定義函數。在函數中,我試圖根據數據集的名稱命名工作表(使用xlsx)。這可能嗎?見例如:如何將數據框的名稱傳遞給Excel工作表(使用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())Getting the name of a data frame但lapply似乎被重命名我的數據幀到X[[i]],然後拋出無效字符的錯誤「[」

+0

這就是'lapply'所做的......沒有辦法從lapply() - ed函數中調用它。相信我......我已經厭倦了一切。在返回結果後,需要使用'setNames'來放置名稱。 –

+0

感謝BondedDust。很遺憾聽到:(。然而,對於setNames,我仍然沒有看到任何方式來命名每個樂曲循環的文件。你呢?我嘗試了使用計數器,但它重置每次運行的樂句。這是否合理?您是否看到解決方案? – dsgeller

回答

0

下面是編輯的代碼,可以讓你訪問列表節點的名稱。發佈前請檢查您的代碼,它包含一些含糊之處。

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") 
相關問題