运行 来自其他 R 脚本的 R markdown (.Rmd) 生成 HTML

Run R markdown (.Rmd) from inside other R script to produce HTML

例如,如果您创建一个新的 R markdown 文件并将其另存为 'test'。然后可以 运行 或从普通 R 脚本中部署此 test.Rmd 文件。目的是在 HTML 中生成输出,而无需打开 .Rmd 文件。

我希望创建一个主文件来一次完成许多降价文件;这将节省大量时间,因为您不必打开许多降价文件并等待每个文件完成。

您正在寻找 rmarkdown::render().

“test.Rmd”的内容

---
title: "Untitled"
output: html_document
---

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

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
summary(cars)
```

script.R

的内容
# provided test.Rmd is in the working directory
rmarkdown::render("test.Rmd")

一种渲染多个 Rmd 的方法

cwd_rmd_files <- list.files(pattern = ".Rmd$")
lapply(cwd_rmd_files, rmarkdown::render)

谢谢the-mad-statter,你的回答很有帮助。我面临的问题要求我动态准备降价。通过调整您的代码,这很容易实现:

“test_dyn.rmd”的内容

---
title: "Untitled"
output: html_document
---

The chunk below adds formatted text, based on your inputs.
```{r text, echo=FALSE, results="asis"}
cat(text)
```

The chunk below uses your input in as code.
```{r results}
y
```

“script_dyn.r”的内容

in_text <- c("**Test 1**", "*Test 2*")
in_y <- 1:2

lapply(1:2, function(x) {
  text <- in_text[[x]]
  y <- in_y[[x]]
  rmarkdown::render(input = "test_dyn.rmd", output_file = paste0("test", x))
})

像这样,您可以在代码中创建具有不同文本和不同变量值的文件。