Display a data frame as table in R Markdown

2019-04-07 22:50发布

问题:

In knitr I want to add a (small) data frame as a table using the kable package:

---
output: html_document
---

```{r}
knitr::kable(mtcars[1:5,1:5], format="html")
```

This returns a compact table as above, while changing it to format="markdown"returns a nice table but spanning the whole page:

I have found the knitr manual but it does not cover the extra formatting options for each format. How can I change the size of a knitr table or even better, where can I get this information from?

回答1:

The general approach would be to use your own custom CSS and include that in the YAML at the start of the document.

You can actually sort of do this from within your document, but I would suggest editing your CSS outside of the document and working from there.

Here's a minimal example:

---
title: "Test"
date: "24 October 2015"
output: 
  html_document:
    css: mystyle.css
---

```{r, results='asis'}
writeLines("td, th { padding : 6px } th { background-color : brown ; color : white; border : 1px solid white; } td { color : brown ; border : 1px solid brown }", con = "mystyle.css")
dset1 <- head(ToothGrowth)
knitr::kable(dset1, format = "html")
```

This should:

  1. Create a file named "mystyle.css" with your relevant CSS styling.
  2. Produce something that looks something like the following.