在Rmarkdown中从`for`循环使用`ggplotly`和`DT` [英] Using `ggplotly` and `DT` from a `for` loop in Rmarkdown

查看:104
本文介绍了在Rmarkdown中从`for`循环使用`ggplotly`和`DT`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在<$ c $中使用 ggplotly() datatable()在RMarkdown中c> for 循环还是函数?示例:

Is that possible to use ggplotly() or datatable() in RMarkdown from inside a for loop or function? Example:

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

这样的问题

I wonder if this is because interactive outputs cannot be print-ed at all - by design.
No such problem existing when printing non-interactive outputs.

PS
这与以下内容有关:
在Rmarkdown中自动生成预格式化文本,使用R

在rmarkdown中循环头文件/节?

推荐答案

这是帖子我在我的评论中根据您的情况添加了

This is the solution from the post I added in my comment adapted to your case:

---
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中从`for`循环使用`ggplotly`和`DT`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆