How to change appearance of table header row with R formattable package

馋奶兔 提交于 2019-12-22 09:48:01

问题


I'm using the formattable package in R to produce a HTML table. I can use formatter to customise the look of data values in in my table e.g. font-size, color etc. But I can't work out how to alter the appearance of the table header row.I can alter the actual column names using col.names(), but haven't been able to change their appearance.

For example, in the table below how can I change the text color or background color in the header row (mpg, cyl, disp etc.)

Ultimately, I plan to use formattable::as.htmlwidget() and library(webshot) to grab an image file of the table, see Command for exporting/saving table made with Formattable package in R

Thanks

library(formattable)

formatRed <- formatter("span"
    , style = x ~ style(color = ifelse(x > 21 , "red", "black")))

formatSize <-  formatter("span"
    , style = x ~ style("font-size" = "8px"))

exTb <- formattable(head(mtcars, 5)
    , table.attr = "class='table table-striped'"
    , list(mpg = formatRed
        , wt = formatSize)
)

exTb

回答1:


You can use a style sheet. You can either embed your style sheet in your .Rmd file, or, you can save your style sheet as a .css file, and then reference it from the .Rmd file. If you want more information about embedding style sheets into your .Rmd file, see this question. If you want more information about referencing an external style sheet, see Section 3.1.4.1. In my example, I'm embedding the style sheet (the <style>...</style> component) in my .Rmd file. My style sheet defines styles to change table headings' fonts to Times New Roman, and table headings' font colours to red.

---
title: "Test"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

<style>
  thead {
     font-family: "Times New Roman";
     color: red;
  }
</style>

```{r, echo=FALSE}
library(formattable)
df <- data.frame(Change = c(1), My = c(2), Style = c(3))
ft <- formattable(df)
ft
```

By extending your style sheet, you can impact other elements in the HTML file.



来源:https://stackoverflow.com/questions/42070506/how-to-change-appearance-of-table-header-row-with-r-formattable-package

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