我正在尝试建立一个knitr::knit_hooks()
自动格式化 R-markdown 块的数据帧输出kableExtra
在我的 HTML 报告中。
我不想重复将以下行(或任何行)添加到每个列表数据块的末尾:
head(iris) %>%
kable("html") %>%
kable_styling("hover", full_width = FALSE)
我想出了一个基于的解决方案这个答案 https://stackoverflow.com/a/19880010/8675075通过评估块来工作source(参见我的回答如下 https://stackoverflow.com/a/52529973/8675075这包括我在这种方法中遇到的一些问题);我希望使用块可能有更好的解决方案output.
这是一个示例 .Rmd,其中概述了我想要实现的目标。
---
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)
```
谢谢。