Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using R-markdown knitr hooks to custom format tables in HTML reports

I am trying to set up a knitr::knit_hooks() to automatically format data frame output of an R-markdown chunk with kableExtra in my HTML report.

I would like to not repeatedly add the following lines (or any lines) to the end of each chunk of tabulated data:

head(iris) %>%
  kable("html") %>%
  kable_styling("hover", full_width = FALSE)

I came up with one solution based on this answer that works by evaluating the chunk source (see my answer below that includes some issues that I have with this approach); I'm hoping there might be a better solution using the chunk output.

Here is an example .Rmd with an outline of what I would like to achieve.

---
title: "Untitled"
author: "Paul"
date: "25 September 2018"
output: html_document
---

```{r setup, include = F}

library(dplyr)
library(kableExtra)
library(knitr)

data(iris)

default_source_hook <- knit_hooks$get('source')

knit_hooks$set(
  output = function(x, options) {
    x %>%
      kable("html") %>%
      kable_styling("hover", full_width = FALSE)
  },
  source = function(x, options) {
    if(is.null(options$table))
      default_source_hook(x, options)
    else {
      eval(parse(text = x)) %>%
        kable("html") %>%
        kable_styling("hover", full_width = F)
    }}
)


```

Desired chunk input:

```{r test, echo = F}
head(iris)

```

Desired output will look like:

```{r output, echo = F}
head(iris) %>%
  kable("html") %>%
  kable_styling("hover", full_width = FALSE)

```

Solution using the source chunk output:

```{r table_format, results = "hide", table = T, eval = F}
head(iris)

```

Thank you.

like image 340
Paul Avatar asked Sep 25 '18 05:09

Paul


1 Answers

If using knit hooks is not necessary, the following might help. The idea is to just define a function that prints whatever it gets exactly the way you want. This does not eliminate all typing, but reduces it substantially.

---
title: "Untitled"
author: "Paul"
date: "25 September 2018"
output: html_document
---

```{r setup, include = F}

library(dplyr)
library(kableExtra)
library(knitr)

tbl_out <- function(data) {
  data %>% kable("html") %>% kable_styling("hover", full_width = FALSE)
}
```

Prints as desired:

```{r test, echo = F}
head(iris) %>% tbl_out()
```

Output:

enter image description here

like image 150
symbolrush Avatar answered Oct 02 '22 15:10

symbolrush