使用列表名称作为使用XLConnect的工作表的名称

时间:2012-03-24 08:15:31

标签: r 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)))

并意识到列的名称正被传递给工作表变量。任何想法如何克服这个?

2 个答案:

答案 0 :(得分:4)

您需要lapply而不是列表:

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

答案 1 :(得分: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)