在Rmarkdown中使用for循环调用`ggplotly`和`DT`。

8

在RMarkdown中,是否可以从for循环或函数内部使用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中循环标题/部分


1
你看过这个吗:https://dev59.com/EJXfa4cB1Zd3GeqPfHNP - J_F
谢谢提供链接,我已经查看了。它确实提供了一个解决方案,但只适用于您只想循环 ggplotly 的情况(为此,您需要停止使用 ggplot2 并直接使用 plotly)。然而,我正在尝试在打印每个章节标题后自动生成文本、图形和表格的组合。 - IVIM
1
你仍然可以使用ggplotly。请参见https://dev59.com/S0wGtIcB2Jgan1znfgJh#61909785。此外,还可以组合不同的htmlwidgets。 - stefan
发现这个相关链接(在 .Rmd 文件中的 for 循环中使用 ggplotly 不起作用)。 https://github.com/ropensci/plotly/issues/570 - 看起来问题仍未解决 :( - IVIM
2个回答

17
这是我在评论中添加的文章所提供的解决方案,适用于您的情况:
---
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)))

}
```

2
这很棒。但是我不明白为什么需要初始化汽车。我在我的电脑上尝试了一下,没有初始化步骤就会失败。我问的原因是因为我有一个复杂的表格列表,使用for循环遍历,但我似乎无法用for循环进行初始化! - Ahdee
删掉上面的注释:要让列表正常工作,只需使用lappy初始化,像这样:l = list ( c=cars, c2=iris ) htmltools::tagList( lapply(l, datatable) ) - Ahdee
2
嗨@Ahdee。我们不需要初始化车辆。初始化步骤确保javascript依赖项,即plotly.js和DataTables.js,包含在html文档中。 - stefan
如果使用 %>% 符号,则为... cars %>% select(all_of(col)) %>% DT::datatable(options = list(paging=F)) %>% print(htmltools::tagList(.)) } - Brian D

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接