使用R-markdown编织钩子定制HTML报表中的格式表 [英] Using R-markdown knitr hooks to custom format tables in HTML reports

查看:138
本文介绍了使用R-markdown编织钩子定制HTML报表中的格式表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置knitr::knit_hooks()以在HTML报告中使用kableExtra自动格式化R-markdown块的数据帧输出.

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)

我提出了一种基于此答案的解决方案,该解决方案通过评估块起作用>(请参阅我的下面的答案,其中包括我使用此方法遇到的一些问题);我希望使用 output 块可能有更好的解决方案.

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.

这里是一个示例.Rmd概述了我想要实现的目标.

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)

```

谢谢.

推荐答案

如果不需要使用编织钩,则以下内容可能会有所帮助.想法是只定义一个函数,该函数将完全按照您想要的方式打印任何内容.这并不能消除所有打字,但会大大减少打字.

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()
```

输出:

这篇关于使用R-markdown编织钩子定制HTML报表中的格式表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆