How to change appearance of table header row with

2019-05-11 13:48发布

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条回答
爷、活的狠高调
2楼-- · 2019-05-11 14:22

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.

查看更多
登录 后发表回答