我在下面提供了一个可重现的小示例。我想为命名 list 中的每个 ggplot 对象在四开中生成选项卡plots。下面的四开文档将在其自己的二级标题中呈现图形,但不会按预期呈现在选项卡中。
---
title: "Untitled"
format: html
---
```{r}
library(tidyverse)
data <- iris %>% as_tibble()
plots <- data %>%
group_nest(Species) %>%
deframe() %>%
map(., ~ {
ggplot(.x, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point()
})
```
# Iris Plots
::: {.panel-tabset}
```{r}
#| column: screen
#| fig-width: 12
#| fig-height: 8
#| fig-align: center
#| results: asis
iwalk(plots, ~ {
cat('## ', .y, '\n\n')
print(.x)
cat('\n\n')
})
```
:::
Run Code Online (Sandbox Code Playgroud)
当块选项(除 results:asis 之外的所有选项)被删除时,文档将按预期正确渲染选项卡内的绘图。
# Iris …Run Code Online (Sandbox Code Playgroud) 是否可以从循环或函数内部使用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 …Run Code Online (Sandbox Code Playgroud)