如何将R数据框保存为Excel文件,某些单元格以粗体显示?

我经常写相关matrix的论文。 我希望能够以xls或xlsx格式将相关matrix导出到Excel。 我也想用大胆的相关关系来格式化(例如> .2)。 我想也许XLConnect可能提供的function。

为了使示例简单,假设数据框如下,并假设我想要加粗所有大于5的单元格。

x <- data.frame(matrix(1:9, nrow = 3)) # > x # X1 X2 X3 # 1 1 4 7 # 2 2 5 8 # 3 3 6 9 

顺便说一下,我注意到已经提出了一些解决scheme,用于cellbolding降价:

  • 如何在rmarkdown中的表格(kable)中加粗单元格?
  • 粗体格式化Rmarkdown表中的重要值

我也发现了这个答案,但这不是一个非常通用的解决scheme,它需要相当多的时间才能适应数据​​框架和格式化规则的一般任务:

通过带条件格式的xlsx将数据框导出到Excel

我在这里创build了@ jota的答案改编的以下函数

 xlsx_boldcells <- function(x, matches, file = "test.xlsx", sheetname = "sheet1") { # x data.frame or matrix # matches: logical data.frame or matrix of the same size indicating which cells to bold # copy data frame to work book and load workbook require(xlsx) write.xlsx(x, file, sheetName=sheetname) wb <- loadWorkbook(file) # specify conditional formatting # Note: this could be modified to apply different formatting # see ?CellStyle fo <- Font(wb, isBold = TRUE) cs <- CellStyle(wb, font=fo) # Get cell references sheets <- getSheets(wb) # get all sheets sheet <- sheets[[sheetname]] # get specific sheet rows <- getRows(sheet, rowIndex=2:(nrow(x)+1)) # get rows cells <- getCells(rows, colIndex = 2:(ncol(x)+1)) # Matches to indexes indm <- data.frame(which(matches, arr.ind = TRUE, useNames = FALSE)) names(indm) <- c("row", "col") # +1 required because row and column names occupy first rows and columns indm$index <- paste(indm$row + 1, indm$col + 1, sep = ".") # apply cell style lapply(indm$index, function(ii) setCellStyle(cells[[ii]],cs)) # save workbook saveWorkbook(wb, file) } 

因此,它可以应用于提出的问题:

  xlsx_boldcells(x, x > 5) 

收益:

大胆的Excel表格

或者,它可以应用于常见的相关性问题(即粗大的相关性,例如,大于.6),如下所示:

 data(mtcars) cors <- round(cor(mtcars), 2) xlsx_boldcells(cors, abs(cors) > .6 & cors!=1, file = "cormatrix.xlsx") 

粗体单元格格式的关联使用xlsx