3

是否可以从循环或函数内部使用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
}
```

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

PS 这与: 使用 rmarkdown 中的 R
Looping headers/sections 自动生成 Rmarkdown 中的预格式化文本?

4

2 回答 2

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

}
```
于 2020-06-26T16:50:14.770 回答
0

这似乎是 RMarkdown 的一个持久问题。然而,这是解决方法,在这里找到:

lotlist = list()

for (VAR in factor_vars) {
    p <- ggplot(mtcars, aes_string(x = "mpg", y = "wt", color = VAR)) + geom_point()
    plotlist[[VAR]] = ggplotly(p)
}
htmltools::tagList(setNames(plotlist, NULL))
于 2020-06-26T16:33:07.780 回答