Datatable 不与 Rmd/RStudio 中的 cat 命令一起打印 [英] Datatable is not printed in combination with cat command in Rmd / RStudio

查看:17
本文介绍了Datatable 不与 Rmd/RStudio 中的 cat 命令一起打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么在下面的 Rmd 代码(使用 RStudio 生成 HTML 报告)中只显示 cat 命令?当我将 cat 命令移到 if 子句之外或将其注释掉时,会打印表格.我相信在使用 library(printr) 时会发生同样的事情,但我还没有用最少的样本证实这一点.

Could someone please explain why in the Rmd code (to generate a HTML report using RStudio) below only the cat command is being displayed? When I move the cat command outside the if clause or comment it out the table is printed. I believe the same thing happens when using library(printr), but I haven't confirmed this with a minimal sample.

似乎if 子句中的代码以某种方式一起解释,并且catdatatable 不兼容.

It seems that the code inside the if clause is somehow interpreted together and that the cat doesn't go well with the datatable.

如果你能给我一些关于如何调试它的线索,那也会很有帮助.因为没有任何警告/错误消息.

If you could give me some clues on how to debug this, it would be helpful, too. As there are no warnings/error messages anywere.

---
title: "test"
output: 
  html_document
---


```{r}
if(TRUE){
  DT::datatable(iris)
  cat("I am here with my cat")
}

```

推荐答案

这和 knitr#1137.HTML 小部件,包括 DT/DataTables,仅在从 顶级 R 表达式生成时才有效.这是因为实际上只有顶级表达式被打印.不在顶层的表达式只会被评估.这两种情况有很大的不同.打印涉及调用打印功能.在大多数情况下,这个函数毫无疑问是 print()(或 show() 用于 S4 对象).在knitr的世界里,它比那更复杂:默认的打印函数是knitr::knit_print,它与print(),但除了生成文本输出之外,它还会做另一件事,即收集正在打印的对象的元数据(例如 HTML 依赖项).编织完成后,rmarkdown 会将元数据解析为适当的 HTML 代码(例如 <script src="dataTables.js"></script> 在 <代码>).

This is essentially the same issue as knitr#1137. HTML widgets, including DT/DataTables, only work when they are generated from top-level R expressions. This is because only top-level expressions are actually printed. Expressions that are not at the top level are only evaluated. There is a big difference between the two cases. Printing involves calling a printing function. In most cases, this function is, not surprisingly, print() (or show() for S4 objects). In the knitr world, it is more complicated than that: the default printing function is knitr::knit_print, which is very similar to print(), but it does one more thing besides generating the text output, which is collecting the metadata (e.g. HTML dependencies) of the objects being printed. After knitting is done, rmarkdown will resolve the meta data into appropriate HTML code (e.g. <script src="dataTables.js"></script> in <head>).

综上所述,如果表达式不在顶层,则既不进行打印也不进行元数据收集,因此无法真正呈现widget.

To sum up, if the expression is not at the top level, neither printing nor metadata collection is done, so there is no way for the widget to be actually rendered.

一个简单的例子来说明这一点:

A simple example to illustrate this:

if (TRUE) {

  1:10  # not printed

  11:20 # printed because this is the visible value returned by if()

}

这篇关于Datatable 不与 Rmd/RStudio 中的 cat 命令一起打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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