r-在Rmarkdown中使用"for"循环中的"ggplotly"和"



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

---
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这与:使用R
Rmarkdown中的循环标题/节自动生成Rmarkdown中的预格式化文本?

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

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

这似乎是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))

最新更新