循环中的 Rmarkdown,"knit html" 按钮的输出与 rmarkdown::render 不同

Rmarkdown in loop, "knit html" button different output than rmarkdown::render

编辑

此问题并非(必然)仅与{htmlTable}有关。当渲染一个使用 {kableExtra} 包 (see also this thread).

设置样式的 html table 时也会发生同样的情况

原题

我在 RMarkdown 中工作,试图在循环中使用 htmlTable 包中的 htmltables 呈现文档。当我在 RStudio 中按下“Knit”按钮时,一切正常。但是当我使用 render() 函数时,循环中的 htmltables 不会被打印出来,但是循环之前的 table 会被打印出来。 我读到“编织”按钮和渲染功能做同样的事情,所以我不明白怎么了?

这是一个 .Rmd 文件的工作示例 hmtlTables:

---
output: html_document
---

## htmlTables


```{r, results='asis'}
library(data.table)
library(htmlTable)
library(ggplot2)
a <- data.table(matrix(seq(1, 100, 5), ncol = 2))
htmlTable(a)
for (i in 10:11) {
    cat( paste('## title no.', i, '\n' ) ) 
    print(ggplot(a*i, aes(x = V1, y = V2)) + geom_point())
    print(htmlTable(a*i))
    cat('\n')
}
```

我需要使用不同的参数自动生成许多报告,所以我需要使用 render()

htmlTable 定义了一个 print 方法,它似乎在新的 window 中打印 table,将 print() 更改为 writeLines() 即可技巧:

---
output: html_document
---

## htmlTables


```{r, results='asis'}
library(data.table)
library(htmlTable)
library(ggplot2)
a <- data.table(matrix(seq(1, 100, 5), ncol = 2))
htmlTable(a)
for (i in 10:11) {
    cat( paste('## title no.', i, '\n' ) ) 
    print(ggplot(a*i, aes(x = V1, y = V2)) + geom_point())
    writeLines(htmlTable(a*i))
    cat('\n')
}
```

不过对我来说还是有点奇怪,因为我相信针织按钮在幕后使用 rmarkdown::render() 但在这种情况下它们有不同的行为。

这取决于检测查看器的方式。
要检查这个:

---
title: "Check viewer"
output: html_document
---

```{r viewer, echo=FALSE}
getOption("viewer")
``` 

使用 knit 按钮:

Check viewer
## NULL

rmarkdown::render:


Check viewer

## function (url, height = NULL) 
## {
##     if (!is.character(url) || (length(url) != 1)) 
##         stop("url must be a single element character vector.", 
##             call. = FALSE)
##     if (identical(height, "maximize")) 
##         height <- -1
##     if (!is.null(height) && (!is.numeric(height) || (length(height) != 
##         1))) 
##         stop("height must be a single element numeric vector or 'maximize'.", 
##             call. = FALSE)
##     invisible(.Call("rs_viewer", url, height, PACKAGE = "(embedding)"))
## }
## <environment: 0x0000020ccb7f26d8>

knit 按钮在没有定义查看器的环境中执行渲染,而 RStudio 控制台中的 rmardown::render 使用交互式查看器。

htmlTable 允许设置 options(htmlTable.cat = TRUE),以便 print 工作,即不使用交互式查看器,参见 ?htmlTable::htmlTable.

The print-function relies on the [base::interactive()] function for determining if the output should be sent to a browser or to the terminal. In vignettes and other directly knitted documents you may need to either set useViewer = FALSE alternatively set options(htmlTable.cat = TRUE).

---
output: html_document
---

## htmlTables


```{r, results='asis'}
options(htmlTable.cat = TRUE)
library(data.table)
library(htmlTable)
library(ggplot2)
a <- data.table(matrix(seq(1, 100, 5), ncol = 2))
htmlTable(a)
for (i in 10:11) {
    cat( paste('## title no.', i, '\n' ) ) 
    print(ggplot(a*i, aes(x = V1, y = V2)) + geom_point())
    print(htmlTable(a*i))
    cat('\n')
}
```