【发布时间】:2020-06-26 08:45:26
【问题描述】:
是否可以在 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
}
```
我想知道这是否是因为 interactive 输出根本不可能是 print-ed - 设计使然。
打印非交互式输出时不存在此类问题。
PS
这与:
Automating the generation of preformated text in Rmarkdown using R
Looping headers/sections in rmarkdown?
【问题讨论】:
-
感谢您的链接 - 我看了看。它确实提供了一个解决方案,但前提是您只想循环 ggplotly(为此,您需要停止使用 ggplot2 并直接使用 plotly)。但是,我正在尝试将文本、图形、表格组合在一起——所有这些都是在打印每个部分标题后自动生成的。
-
你仍然可以使用 ggplotly。见stackoverflow.com/questions/61906480/…。也可以组合不同的htmlwidgets
-
找到此相关链接(
for内部的ggplotly.Rmd文件中的循环不起作用)。 github.com/ropensci/plotly/issues/570 - 好像还没有解决:(
标签: r r-markdown dt ggplotly r-glue