How to specify table stripe colors for knitr::kabl

2019-08-03 18:50发布

问题:

How was this person able to make the tables shown in this link? It doesn't look like they were passing any arguments to kable.

Here is the example:

回答1:

The styles of kable tables are controlled by CSS file. tbody can be used to change the colour of the content of the table, with thead able to change the header.

As shown by Lee S, you can create an external CSS file. However, you can also include the CSS directly within the R Markdown file, as markdown accepts raw HTML and passes it through unaltered. See here for some more details

Here is a full reproducible example:

---
output: html_document
---

# Test Project

<style>
   tbody tr:nth-child(odd){
    background-color: #F7FBFF;
  }
</style>


```{r}
knitr::kable(mtcars[1:5, 1:5])
```

This guide provides a good explanation of the table elements which can be controlled by CSS.



回答2:

Download the RMD file http://www.reed.edu/data-at-reed/software/R/blogposts/tables_blogpost.Rmd

Change beginning of RMD file to this:

---
output: 
  html_document:
    keep_md: true
    css: mystyles.css
---

Create a css file called mystyles.css with following contents:

tbody tr:nth-child(odd){
  background-color: #F7FBFF;
}

Save to the same location as your RMD file.