如何使用 rmarkdown 在 pdf 中呈现 DT::datatables?

Posted

技术标签:

【中文标题】如何使用 rmarkdown 在 pdf 中呈现 DT::datatables?【英文标题】:how to render DT::datatables in a pdf using rmarkdown? 【发布时间】:2017-11-16 13:14:44 【问题描述】:

如何将rmarkdown 脚本中的DT::datatable 对象显示到pdf 文档上?到目前为止,我的代码因以下错误而崩溃:

processing file: reportCopy.Rmd
output file: reportCopy.knit.md
Functions that produce html output found in document targeting latex output.
Please change the output type of this document to HTML.

在 YAML 标头中包含 always_allow_html: yes 会抑制错误,但 pdf 上不会出现任何内容。

如果有任何帮助,我将不胜感激。我的代码目前是:

---
title: "DT"
output: pdf_document
---

### Chart 1
```r
DT::datatable(head(mtcars))
```

(我不知道这是否重要,但我的数据表实际上是在 shiny 应用程序中创建的。理想情况下,我希望将预渲染表简单地转储到 rmarkdown 脚本中......但是我改变了策略,现在尝试直接在rmarkdown 代码中呈现表格)

【问题讨论】:

如果你对谁在渲染表格很灵活,有 other table options 用于 R Markdown,比如 knitr::kable @AdamSpannbauer 感谢您的回答。我想我可能确实必须切换到 kable.. 但我宁愿不这样做,因为整个代码库(来自 Shiny 应用程序)是使用 DT::datatables 编写的。 你不能在pdf_document中使用`datatable`(datatable是交互式的),只能在html_document中使用! PDF 的唯一可能性是使用kable 或例如pandoc.table @Malvina_a 感谢您的评论....这是我最担心的。如果您确定,请不要犹豫,将其作为答案,我会接受。 【参考方案1】:

从 knitr v1.13 开始,HTML 小部件将自动呈现为通过 webshot 包截取的屏幕截图。

你需要安装 webshot 包和 PhantomJS:

install.packages("webshot")
webshot::install_phantomjs()

(见https://bookdown.org/yihui/bookdown/html-widgets.html)

【讨论】:

不幸的是,我无法执行第二行代码(我在***.com/questions/44563874/… 提出了这个问题,但尚未得到答复)。但我很高兴知道最初的问题存在解决方案! `````````` '''r chunklabel, echo=FALSE, cache=FALSE, warning = FALSE, message = FALSE, tidy=TRUE library(DT) library (webshot) if(is.null(webshot:::find_phantom()))webshot::install_phantomjs() DT::datatable(iris) ''' ``````````【参考方案2】:

您不能在pdf_document 中使用datatabledatatable 是交互式的,pdf 是静态的),只能在 html_document 中使用! PDF 的唯一可能性是使用kable 或例如pandoc.table

--> 如果你真的想看看datatable 并且正如你所说的datatable 是在shiny 应用程序中创建的,那么你可以看看@987654329 @ 包,它将从 shiny 应用程序创建您的 datatable 的屏幕截图,您可以在 pdf 中进一步将其用作图像。

【讨论】:

以上是关于如何使用 rmarkdown 在 pdf 中呈现 DT::datatables?的主要内容,如果未能解决你的问题,请参考以下文章

如何在rmarkdown中呈现复杂表?

在 for 循环 r markdown 中包含两个变量之间的空格(pdf 输出)

更改 rmarkdown 生成的 PDF 中的字体

如何通过 rmarkdown 在 PDF 中放置表格或更精确地格式化标题文本?

在knitr / rmarkdown中作为png plotly

使用没有 PDF 导航按钮的 rmarkdown 渲染导出为 PDF