我创建了以下根据@jota 的回答改编的函数here
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)
产生:
或者它可以应用于常见的相关性问题(即,加粗大相关性,例如,大于 0.6),如下所示:
data(mtcars)
cors <- round(cor(mtcars), 2)
xlsx_boldcells(cors, abs(cors) > .6 & cors!=1, file = "cormatrix.xlsx")