【发布时间】:2018-09-25 05:50:48
【问题描述】:
我正在尝试设置一个knitr::knit_hooks(),以便在我的 HTML 报告中使用kableExtra 自动格式化 R-markdown 块的数据框输出。
我不想在每个列表数据块的末尾重复添加以下行(或任何行):
head(iris) %>%
kable("html") %>%
kable_styling("hover", full_width = FALSE)
我想出了一个基于this answer 的解决方案,它通过评估块source 来工作(请参阅我的answer below,其中包括我在使用这种方法时遇到的一些问题);我希望使用块 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)
```
谢谢。
【问题讨论】:
标签: r hook r-markdown knitr