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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With