我希望能够通过循环创建RMarkdown代码块。我尝试使用for
循环来实现,但是没有取得太多成功。我认为这可能可以通过lapply
来实现,就像在Shiny应用程序中创建UIs
一样。然而,到目前为止,我还没有取得任何成功。
Reprex:
---
title: "Untitled"
output:
html_document:
theme: united
highlight: tango
toc: true
toc_float:
collapsed: false
smooth_scroll: false
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
```
```{r}
library(dplyr)
library(ggplot2)
df <- datasets::iris %>%
dplyr::as_tibble()
```
## setosa
```{r}
df %>%
dplyr::filter(Species == "setosa") %>%
ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) +
ggplot2::geom_point()
```
## versicolor
```{r}
df %>%
dplyr::filter(Species == "versicolor") %>%
ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) +
ggplot2::geom_point()
```
## virginica
```{r}
df %>%
dplyr::filter(Species == "virginica") %>%
ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) +
ggplot2::geom_point()
```
我的目标是用循环创建标题(setosa、versicolor和virginica)和块。
例如:
for(i in c("setosa", "versicolor", "virginica")) {
## i
df %>%
dplyr::filter(Species == i) %>%
ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) +
ggplot2::geom_point()
}
有什么想法可以实现这个吗?