使用结果='asis'以编程方式插入标头并使用R降价在同一代码块中绘图 [英] Programmatically insert header and plot in same code chunk with R markdown using results='asis'

查看:103
本文介绍了使用结果='asis'以编程方式插入标头并使用R降价在同一代码块中绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rmarkdown中的results = 'asis'块选项使您可以轻松地动态创建包括标题的文本.但是,我希望使用asis选项动态创建标头,然后在同一代码块中插入一些图形.

The results = 'asis' chunk option within Rmarkdown allows one to easily dynamically create text including headers. However, I wish to dynamically create a header with the asis option, but then in the same code chunk insert some graphics.

为此,我可以找到最相关的答案:以编程方式插入带有R减价的文本,标题和列表,但该问题的答案不允许在这些动态标题中同时包含动态标题和图表.

The most related answer I could find for this is here: Programmatically insert text, headers and lists with R markdown, but the answer to this question does not allow both dynamic headers and plots within those dynamic headers.

这是一个简单的可复制示例,下面演示了results = 'asis'

Here is a simple reproducible example follows demonstrating what I can and cannot achieve with results = 'asis'

下面的代码符合我的期望,为每个物种创建了一个标题.

The code directly below does what I would expect, creating a header for each Species.

---
output: html_document
---
```{r echo = FALSE, results ='asis'}
for(Species in levels(iris$Species)){
  cat('#', Species, '\n')
}
```

下面的代码不符合我的要求.理想情况下,下面的代码将为每个物种生成一个标头,并在每个标头下方绘制一个图.而是在输出文件中生成单个setosa标头,后跟三个图.

The code directly below here does not do what I would like. Ideally, the code directly below would generate a header for each Species with a plot underneath each header. Instead, it generates the single setosa header in the output file followed by the three plots.

---
output: html_document
---
```{r echo = FALSE, results ='asis'}
library(ggplot2)
for(Species in levels(iris$Species)){
  cat('#', Species, '\n')
  p <- ggplot(iris[iris$Species == Species,], aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_point()
  print(p)
}
```

是否有某种方法可以动态生成3个标头,每个标头下都有一个图?

Is there some way to dynamically generate the 3 headers with a plot under each header?

推荐答案

您需要使用cat('\n'):

```{r echo = FALSE, results ='asis'}
library(ggplot2)
for(Species in levels(iris$Species)){
  cat('\n#', Species, '\n')
  p <- ggplot(iris[iris$Species == Species,], aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_point()
  print(p)
  cat('\n')
}

这篇关于使用结果='asis'以编程方式插入标头并使用R降价在同一代码块中绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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