【问题标题】:Clash when exporting excel file using "xlsx" and "openxlsx" packages in R在 R 中使用“xlsx”和“openxlsx”包导出 excel 文件时发生冲突
【发布时间】:2017-07-04 11:40:55
【问题描述】:

我有一个大小类似于下面“a”的数据

library(openxlsx)
a <- list()
names(a) <- paste("sheet", seq_along(fulldata), sep="_")  ### name for each sheet
for (i in 1:172) {
a[[i]] <- matrix(i,30,60)
}

write.xlsx(a, "a.xlsx")

如果我运行上面的代码,几秒钟后,R 会自动关闭。

library(xlsx)
options(java.parameters = "-Xmx4000m")
a <- list()
for (i in 1:172) {
a[[i]] <- matrix(i,30,60)
}
n <- paste("sheet", seq_along(fulldata), sep="_") ### name for each sheet

for (i in 1:172) {
write.xlsx(a[[i]], "c.xlsx", sheetName=n[[i]], append=TRUE)
}

如果我运行上面的代码,10 分钟后,它会返回关于内存不足的错误。 我用过

options(java.parameters = "-Xmx4000m") 

要增加要使用的内存,但仍然显示内存不足。
它们都适用于小数据,但当我尝试一次导出 172 张纸时它不起作用。我需要将所有 172 张工作表包含在一个 Excel 文件中。

【问题讨论】:

    标签: r excel export xlsx


    【解决方案1】:

    使用 lapply 创建工作表可能有助于缓解内存问题。

    library(xlsx)
    
    # Create the list of matrices
    a <- list()
    for (i in 1:172) {
      a[[i]] <- matrix(i,30,60)
    }
    
    # Set names for the matrices
    names(a) <- seq_along(a)
    
    # Create a workbook object
    wb <- createWorkbook()
    
    # Add each matrix to it's own worksheet inside of the workbook
    lapply(seq_along(a), function(matrices, matrix.names, i){
                           ws <- createSheet(wb, matrix.names[[i]])
                           addDataFrame(matrices[[i]], ws)
                         }, matrices = a, matrix.names = names(a))
    
    # Set the file path to save the workbook to
    (output.path <- file.path(tempdir(), "output.xlsx"))
    
    # Save the workbook
    saveWorkbook(wb, output.path)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多