[英]How to save an R data frame to Excel file with certain cells in bold?
我经常用相关矩阵写论文。 我希望能够以xls或xlsx格式将相关矩阵导出到Excel。 我还想格式化符合阈值的粗体相关(例如,> .2)。 我想也许XLConnect可能提供功能。
为了使示例简单,假设数据帧如下,并假设我想加粗大于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
顺便说一下,我注意到已经提出了用于降价的单元格的解决方案:
我也找到了这个答案,但它不是一个非常通用的解决方案,因为它需要相当多的时间来适应采用数据框和格式化规则的一般任务:
我创建了以下函数,该函数改编自@ 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)
收益:
或者它可以应用于常见的相关性问题(即,粗体大的相关性,例如,大于.6),如下所示:
data(mtcars)
cors <- round(cor(mtcars), 2)
xlsx_boldcells(cors, abs(cors) > .6 & cors!=1, file = "cormatrix.xlsx")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.