在 Rmarkdown 的 for 循环中使用 ggplotly 和 DT

IVI*_*VIM 3 r r-markdown dt ggplotly r-glue

是否可以从循环或函数内部使用ggplotly()datatable()在 RMarkdown 中for?例子:

---
title: "Using `ggplotly` and `DT` from a `for` loop in Rmarkdown"
output: html_document
---

```{r setup, include=FALSE}
library(ggplot2); library(DT)
```

## Without `for` loop - works

```{r}
datatable(cars)

g <- ggplot(cars) + geom_histogram(aes_string(x=names(cars)[1] ))
ggplotly(g) 
```

## From inside the `for` loop  - does not work (nothing is printed)

```{r}
for( col in 1:ncol(cars)) {

  datatable(cars)          # <-- does not work 
  print( datatable(cars) ) # <-- does not work either

  g <- ggplot(cars) + geom_histogram(aes_string(x=names(cars)[col] ) )

  ggplotly (g)            # <-- does not work 
  print ( ggplotly (g) )  # <-- does not work either
}
```
Run Code Online (Sandbox Code Playgroud)

我想知道这是否是因为交互式输出根本无法print通过设计进行编辑。
打印非交互式输出时不存在此类问题。

PS 这与: Automating the generation of preformatted text in Rmarkdown using R
Looping headers/sections in rmarkdown?

ste*_*fan 6

这是我在评论中添加的帖子中的解决方案,适用于您的情况:

---
title: "Using `ggplotly` and `DT` from a `for` loop in Rmarkdown"
output: html_document
---

```{r setup, include=FALSE}
library(plotly); library(DT)
```

```{r, include=FALSE}
# Init Step to make sure that the dependencies are loaded
htmltools::tagList(datatable(cars))
htmltools::tagList(ggplotly(ggplot()))
```

```{r, results='asis'}
for( col in 1:ncol(cars)) {
  
  print(htmltools::tagList(datatable(cars)))
  
  g <- ggplot(cars) + geom_histogram(aes_string(x=names(cars)[col] ) )

  print(htmltools::tagList(ggplotly(g)))

}
```
Run Code Online (Sandbox Code Playgroud)

  • 这很棒。但是我不明白为什么需要启动汽车。我在我的电脑上尝试过,如果没有初始化步骤,它就会失败。我问的原因是因为我有一个使用 for 循环的复杂表列表,而且我似乎无法启动 for 循环! (2认同)
  • 嗨@Ahdee。我们不需要启动汽车。init 步骤确保 javascript 依赖项(即plotly.js 和DataTables.js)包含在html 文档中。 (2认同)