将自定义函数传递给 RMarkdown YAML df_print 用于在编织 HTML 输出时打印数据帧

Pass custom function to RMarkdown YAML df_print for printing dataframes when knitting HTML output

这是我在 Stack Overflow 上的第一个 posting,所以如果这是一个 ill-formed 或 non-reproducible 问题,请原谅我。我正在尝试将以下自定义数据 table 打印函数 ('print.me') 传递给 RMarkdown 中的 YAML header,以便 df_print 编织到 HTML:

print.me <- function(x) {
  x <- x %>% kbl(digits=2, align= 'l', booktabs=T) %>% 
   kable_styling(fixed_thead = T, position ="float_right") %>% 
   kable_paper("striped", full_width = T, fixed_thead = T, 
   html_font = "Helvetica", font_size = 11) %>% 
   row_spec(0, color = "yellow", background = "#5b705f", font_size = 12) %>% 
   scroll_box(width = "700px", height = "300px")
   return(x)
}

当从 RMarkdown 打印 mtcars 时,此函数成功呈现了我希望的数据帧格式:

问题是我想不出一种方法来成功地将 'print.me' 传递给 YAML header 以便 'print.me' 成为编织到 [= 时呈现数据帧的默认方法36=]。我在 YAML header 中的代码如下所示:

df_print: !expr 'print.me'

但是,我收到以下错误消息:

Error: object 'print.me' not found Error in yaml::yaml.load(..., eval.expr = TRUE) : Could not evaluate expression: print.me Calls: ... parse_yaml_front_matter -> yaml_load -> Execution halted

df_print文档声称可以将任意函数传递给df_print,我发现过去post似乎已经达到了解决方法,但我我这辈子都想不出如何从 header 调用这个函数。谢谢你的帮助! ~杰米

我在 GitHub 的 rmarkdown documentation but I don't think it's recommended to pass a complex function like yours to the df_print argument in the YAML header. However, according to this 问题中找不到这个 print.me() 的(简化版本)它是这样的:

---
title: "testprint" 
output: 
  html_document:
    df_print: !expr print.me <- function(x, ...) { knitr::asis_output(kableExtra::kbl(x, digits=2, align= 'l'))}
---

相反,您可以在代码块中注册自己的打印数据帧的方法(最好在 YAML header 之后),如下所示:

```{r setup, include=FALSE}
library(kableExtra)
library(knitr)

print.me <- function(x, ...) {
   x %>% 
   kbl(digits=2, align= 'l', booktabs=T) %>% 
   kable_styling(fixed_thead = T, position ="float_right") %>% 
   kable_paper("striped", full_width = T, fixed_thead = T, 
               html_font = "Helvetica", font_size = 11) %>% 
   row_spec(0, color = "yellow", background = "#5b705f", font_size = 12) %>% 
   scroll_box(width = "700px", height = "300px") %>% 
   asis_output()
}

registerS3method("knit_print", "data.frame", print.me)
```

技术细节有点复杂。简而言之,我们用自定义覆盖检查 object 的 class 时调用的默认函数(极客调用此过程 method dispatch)函数并将此方法注册到 knitr.