runlevel0
runlevel0

Reputation: 2993

Display a data frame as table in R Markdown

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")
```

enter image description here

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

enter image description here

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?

Upvotes: 23

Views: 59877

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193677

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.

enter image description here

Upvotes: 23

Related Questions