Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `ggplotly` and `DT` from a `for` loop in Rmarkdown

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

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 This is related to: Automating the generation of preformated text in Rmarkdown using R
Looping headers/sections in rmarkdown?

like image 280
IVIM Avatar asked Mar 24 '26 05:03

IVIM


1 Answers

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

}
```
like image 74
stefan Avatar answered Mar 25 '26 21:03

stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!