r - 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"
解决方案
这是一个解决方案,不确定它是否适合您的用例,但它确实成功呈现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)
这给了我们:
推荐阅读
- c# - 属性是否隐式初始化变量?
- node.js - if语句中的NodeJS猫鼬错误
- reactjs - 反应路由器、重定向、firebase auth 和私有路由:管理它的最佳方式
- python - 有人可以帮我找出我写的主要生成器函数中的错误吗
- php - PhpStorm 代码检查返回“非法数组键类型浮点数”
- reactjs - 输入代码时将数据加载到输入中
- android - Android App A如何通过点击Android A中的按钮将Android B的形式带到前面
- php - 修改 Woocommerce 模板文件以按产品类别显示产品
- ruby-on-rails - 如何为 Rails 应用程序建模公共信息
- java - InitBinder 将验证器绑定到某些参数