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()
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…