在循环中创建 RMarkdown 块 [英] Create RMarkdown chuncks in a loop

查看:50
本文介绍了在循环中创建 RMarkdown 块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够循环创建 RMarkdown 块.我曾尝试通过 for 循环执行此操作,但没有取得多大成功.我想这可能可以通过 lapply 实现,就像在闪亮的应用程序中创建 UI 一样.但是,到目前为止,我还没有取得任何成功.

I would like to be able to create RMarkdown chuncks in a loop. I have tried doing this through a for loop, without much success. I imagine this could probably be possible through lapply, as one would do for creating UIs in a shiny app. However, I haven't had any success so far.

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)和大块.

My goal is to create the headings (setosa, versicolor, and virginica) and the chuncks with a loop.

例如:

for(i in c("setosa", "versicolor", "virginica")) {

  ## i

  df %>% 
    dplyr::filter(Species == i) %>% 
    ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) + 
    ggplot2::geom_point()
}

关于如何实现这一点有什么想法吗?

Any ideas on how accomplish this?

推荐答案

如果你想在循环中创建标题 + 输出,你可以这样做:

If you want to create headings + outputs within a loop, you can do:

```{r species_loop, results='asis'}
for(i in c("setosa", "versicolor", "virginica")) {

  cat(paste0("\n\n## ", i, "\n"))

  p <- df %>% 
    dplyr::filter(Species == i) %>% 
    ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) + 
    ggplot2::geom_point()
  print(p)
}
```

所以:

  • 使用 results='asis' 允许将您 cat() 的输出解释为 Markdown 语法
  • cat()使用所需的 Markdown 语法来生成标题(由一些换行符包围以确保正确解释)
  • 显式print()在循环内绘制绘图.
  • Using results='asis' to allow output that you cat() to be interpreted as Markdown syntax
  • cat()ing the required markdown syntax to produce the headers (surrounded by some newlines to make sure it's interpreted properly)
  • Explicitly print()ing the plot within the loop.

这篇关于在循环中创建 RMarkdown 块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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