Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

r - Datatable is not printed in combination with cat command in Rmd / RStudio

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.

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")
}

```
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>).

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...