Color and Style Format Data.Frames in R

我只是一个虾纸丫 提交于 2019-12-24 12:12:01

问题


I am trying to format a data.frame I have created in R and can not seem to find a solution. By format I mean that I would like to bold/italicize the headers(i.e. names) of the data.frame and also color/highlight certain rows within the data.frame.

I tried researching on google/stackoverflow, but I could not find something applicable or directly useful. I also tried using CellStyle, but that would not allow me to bold/italicize the headers of the data.frame.

Any help is appreated!


回答1:


You can go a long way with XLConnect package to format a data frame in Excel.

Here is code I have been using, which would be a good starting point for you learning it and exploring changes to suit you. Usage: save.xls(your data frame, the name you want to give the file with the .xlsx suffix, ....

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)
}


来源:https://stackoverflow.com/questions/29021090/color-and-style-format-data-frames-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!