簡體   English   中英

在R中使用“ xlsx”和“ openxlsx”包導出Excel文件時發生沖突

[英]Clash when exporting excel file using “xlsx” and “openxlsx” packages in R

我有一個數據,其大小類似於下面的“ 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文件中。

使用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)

暫無
暫無

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

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