r - 使用 write.xlsx 处理空数据帧

标签 r loops r-xlsx

当我在循环中使用 write.xlsx 时,如何处理空数据帧?

下面是循环的样子,其中 source("./Scripts/Analysis_details.R") 引用了创建数据框的 r 文件。

library(xlsx) 
    for (A in unique(df_base$A)) {
          df<- df_base[df_base$A==A,]
          source("./Scripts/Analysis_details.R")
          output_file = paste("./Output/report_", A, '_', Sys.Date(), ".xlsx", sep='')
          write.xlsx(df1, file=output_file, sheetName="df1", append=TRUE, row.names=FALSE, showNA = FALSE)
          write.xlsx(df2, file=output_file, sheetName="df2", append=TRUE, row.names=FALSE, showNA = FALSE)
          write.xlsx(df3, file=output_file, sheetName="df3", append=TRUE, row.names=FALSE, showNA = FALSE)
          write.xlsx(df4, file=output_file, sheetName="df4", append=TRUE, row.names=FALSE, showNA = FALSE)}

我得到的错误是......

Error in mapply(setCellValue, cells[seq_len(nrow(cells)), colIndex[ic]],  : zero-length inputs cannot be mixed with those of non-zero length

最佳答案

我可以通过将修改后的 write.xlsx() 函数放入我的脚本来解决此问题。如果数据框有零行,则跳过 .write_block() 并仅使用列名保存文件。请注意,您还必须将原始 .write_block() 函数也复制到您的脚本中。

write.xlsx.custom <- function(x, file, sheetName="Sheet1",
                       col.names=TRUE, row.names=TRUE, append=FALSE, showNA=TRUE)
{
    if (!is.data.frame(x))
        x <- data.frame(x)    # just because the error message is too ugly

    iOffset <- jOffset <- 0
    if (col.names)
        iOffset <- 1
    if (row.names)
        jOffset <- 1

    if (append && file.exists(file)){
        wb <- loadWorkbook(file)
    } else {
        ext <- gsub(".*\\.(.*)$", "\\1", basename(file))
        wb  <- createWorkbook(type=ext)
    }  
    sheet <- createSheet(wb, sheetName)

    noRows <- nrow(x) + iOffset
    noCols <- ncol(x) + jOffset
    if (col.names){
        rows  <- createRow(sheet, 1)                  # create top row
        cells <- createCell(rows, colIndex=1:noCols)  # create cells
        mapply(setCellValue, cells[1,(1+jOffset):noCols], colnames(x))
    }
    if (row.names)             # add rownames to data x                   
        x <- cbind(rownames=rownames(x), x)

    if(nrow(x) > 0) {
        colIndex <- seq_len(ncol(x))
        rowIndex <- seq_len(nrow(x)) + iOffset

        .write_block(wb, sheet, x, rowIndex, colIndex, showNA)
    }
    saveWorkbook(wb, file)

    invisible()
}

我在 https://github.com/cran/xlsx/blob/master/R/write.xlsx.R 找到了原始函数

关于r - 使用 write.xlsx 处理空数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46490452/

相关文章:

Linux:查找文件时使用文件夹名循环

javascript - for循环 react

php - 创建类别树的最佳方法

R read.xlsx colClasses 问题

r - 如何从R中的字符串中检索某些字符?

r - dbplyr 将字符更改为临时表中的日期格式

r - 通过R中的4步以交替方式组合2个向量

r - 提高 RStudio 图形设备的质量(预览)