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?
这是我在评论中添加的帖子中的解决方案,适用于您的情况:
---
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)