R中的颜色和样式格式Data.Frames

时间:2015-03-12 22:01:48

标签: r format dataframe

我正在尝试格式化我在R中创建的data.frame,似乎无法找到解决方案。格式化我的意思是我想粗体/斜体化data.frame的标题(即名称),并在data.frame中着色/突出显示某些行。

我尝试过研究google / stackoverflow,但我找不到适用的或直接有用的东西。我也尝试过使用CellStyle,但这不允许我粗体/斜体化data.frame的标题。

任何帮助都得到了应对!

1 个答案:

答案 0 :(得分:2)

您可以使用XLConnect包在Excel中格式化数据框。

这是我一直在使用的代码,这将是您学习它并探索适合您的更改的良好起点。用法:save.xls(您的数据框,您要为该文件指定.xlsx后缀的名称,....

save.xls <- function(df, filename, sheetname="Sheet", create=TRUE, rownames=NULL, startRow=1, zebra=F) {
  require(XLConnect)
  require(stringr)

  if (is.matrix(df)) df <- as.data.frame(df)

  if (!str_detect(filename, "\\.xlsx$")) filename <- str_c(filename, ".xlsx")

  wb <- loadWorkbook(filename, create=create)

  if (existsSheet(wb, sheetname))
    warning(sprintf("Sheet %s already existed and was overwritten", sheetname))

  createSheet(wb, name=sheetname)
  if (!is.null(rownames)) df <- transform(df, rownames = row.names(df))
  writeWorksheet(wb, df, startRow=startRow, sheet=sheetname, rownames=rownames)

  if (zebra) {
    color <- createCellStyle(wb)
    setFillForegroundColor(color, color = XLC$"COLOR.LIGHT_CORNFLOWER_BLUE")
    setFillPattern(color, fill = XLC$FILL.SOLID_FOREGROUND)

    for (i in 1:ncol(df)) {
      setCellStyle(wb, sheet = sheetname, row = seq(startRow+1, nrow(df)+2, 2), col = i, 
                   cellstyle = color)
    }

    #prcntg <- createCellStyle(wb)  see my script of XLConnect.R for how it worked
    #dollar <- createCellStyle(wb)
    #setDataFormat(prcntg, format = "0.0")
    #setDataFormat(dollar, format = "$ 0.00")

    border <- createCellStyle(wb)
    setBorder(border, side = c("bottom","top"), type = XLC$"BORDER.THICK", color = XLC$"COLOR.RED")
    setCellStyle(wb, sheet = "Sheet", row = startRow, col = 1:ncol(df), cellstyle = border)
    setColumnWidth(wb, sheet = "Sheet", column = 1:ncol(df), width = -1) # this autosizes each column
  }

  saveWorkbook(wb)
}