2012-03-24 138 views
2

正如標題所示,我想這樣做。下面的例子:使用列表名稱作爲使用XLConnect的工作表名稱

library(stringr) 
library(XLConnect) 

df <- data.frame(do.call("rbind", lapply(1:10, function(i) rnorm(10)))) 
df.list <- rep(list(df), 10) 
names(df.list) <- paste("DataFrame", str_pad(1:length(df.list), 2, pad = "0"), sep = "") 

df.list.workbook <- loadWorkbook("df.list.workbook.xlsx", create = TRUE) 
lapply(1:length(df.list), function(i) createSheet(df.list.workbook, name = names(df.list[i]))) 
lapply(df.list[1:length(df.list)], function(i) writeWorksheet(df.list.workbook, i, sheet = names(i))) 

最後一行是它拋出了一個錯誤:

Error: IllegalArgumentException (Java): Sheet index (-1) is out of range (0..9) 

要解決這一點,我想:

lapply(df.list[1:length(df.list)], function(i) print(names(i))) 

,實現了列的名稱被傳遞給表單變量。任何想法如何克服這一點?

+0

'名(df.list)[I]'? – James 2012-03-24 08:29:00

+0

@詹姆斯,給我'在打印錯誤(名稱(df.list)[i]): 在選擇函數'print'的方法中評估參數'x'時出錯:名稱中的錯誤(df.list) [i]:無效的下標類型'list'' – Ben 2012-03-24 08:32:20

+0

啊,我明白了。還需要更改爲:'lapply(seq_along(df.list),function(i)writeWorksheet(df.list.workbook,df.list [[i]],sheet = names(df.list)[i]) '。需要在索引而非列表上使用 – James 2012-03-24 08:38:27

回答

4

您需要lapply超過指數,而不是名單:

lapply(seq_along(df.list), function(i) writeWorksheet(df.list.workbook, df.list[[i]], sheet = names(df.list)[i])) 
2

XLConnect在很多地方量化。你的情況,這對於createSheetwriteWorksheet,所以你可以寫:

df.list.workbook <- loadWorkbook("df.list.workbook.xlsx", create = TRUE) 
createSheet(df.list.workbook, name = names(df.list)) 
writeWorksheet(df.list.workbook, data = df.list, sheet = names(df.list)) 
saveWorkbook(df.list.workbook)