gpt4 book ai didi

r - 在 Rmarkdown 中使用 `ggplotly` 循环中的 `DT` 和 `for`

转载 作者:行者123 更新时间:2023-12-04 00:58:08 26 4
gpt4 key购买 nike

是否可以使用 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
}
```
我想知道这是不是因为交互式输出不能 print -ed 完全 - 按设计。
打印非交互式输出时不存在此类问题。
聚苯乙烯
这与:
Automating the generation of preformated text in Rmarkdown using R
Looping headers/sections in rmarkdown?

最佳答案

这是来自 post 的解决方案我在我的评论中添加了适合您的案例:

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

}
```

关于r - 在 Rmarkdown 中使用 `ggplotly` 循环中的 `DT` 和 `for`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60685631/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com