首页 > 解决方案 > rmarkdown 执行变量内的代码

问题描述

我有类似于以下的代码,它是动态生成并存储在变量中的:

---
title: "test"
author: "me"
date: "3 June 2019"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r, comment=""}
for (i in 1 :  3) { 
  cat('\n') 
  print(summary(iris[i*50 : 50, "Sepal.Length"] ))
}
```

假设它存储在一个名为rmkdown_code

现在,我需要能够执行此变量中的代码并将其呈现为 html 或 pdf。我知道这些results = asis选项,并且我尝试了它的不同变体。但是,我仍然无法让上面的代码在 html 中呈现。html页面出现在rstudio中,它显示了rmkdown_code变量的内容。它只是不执行它。

我需要将 的内容rmkdown_code呈现为好像来自平面文件一样。

我尝试了以下方法,但都没有奏效。有些更好地格式化了文本,但没有绘制图表。我想避免将rmkdown_code变量的内容写入平面文件。

```{r,echo=FALSE,eval=TRUE}
knitr::knit_expand(text=rmkdown_code)

#eval(parse(text = rmkdown_code))
#eval(c(paste0("- `", rmkdown_code, "`"), sep = "\n"))
#eval(knitr::asis_output(rmkdown_code))
#res <- knitr::knit_expand(text=rmkdown_code);knitr::knit(text=res, quiet=F)
# knitr::inline_expr("2+2")
```

输出dput(rmarkdown)

## "---\ntitle: \"test\"\nauthor: \"me\"\ndate: \"3 June 2019\"\noutput: html_document\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n```{r, comment=\"\"}\nfor (i in 1 :  3) { \n  cat('\\n') \n  print(summary(iris[i*50 : 50, \"Sepal.Length\"] ))\n}\n```\n"

标签: rr-markdownknitrrscript

解决方案


这是一个解决方案,不确定它是否适合您的用例,但它确实成功呈现rmkdown_code为 HTML 报告。

确保您设置了工作目录或正在项目中工作,因为 .rmd 将呈现到您当前的 wd。

rmkdown_code <- "---\ntitle: \"test\"\nauthor: \"me\"\ndate: \"3 June 2019\"\noutput: html_document\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n```{r, comment=\"\"}\nfor (i in 1 :  3) { \n  cat('\\n') \n  print(summary(iris[i*50 : 50, \"Sepal.Length\"] ))\n}\n```\n"

render_func <- function(x){
  writeLines(x, "temp.rmd")
  rmarkdown::render("temp.rmd")
}

render_func(rmkdown_code)

这给了我们:


推荐阅读