Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 527
runlevel0 Avatar asked Oct 24 '15 14:10

runlevel0


People also ask

How do I display data in R markdown?

By default, R Markdown displays data frames and matrixes as they would be in the R terminal (in a monospaced font). If you prefer that data be displayed with additional formatting you can use the knitr::kable function, as in the . Rmd file below. This file is available here on RStudio Cloud.

How do you display a table in Markdown?

Tables. To add a table, use three or more hyphens ( --- ) to create each column's header, and use pipes ( | ) to separate each column. For compatibility, you should also add a pipe on either end of the row.

What does Kable do in R?

The kable() function in knitr is a very simple table generator, and is simple by design. It only generates tables for strictly rectangular data such as matrices and data frames.


1 Answers

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

like image 61
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 30 '22 00:09

A5C1D2H2I1M1N2O1R2T1