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

Viewed 2779

As the example, if you create a new R markdown file and save it as 'test'. Can one then run or deploy this test.Rmd file from within a normal R script. The purpose being to generate the output in HTML, without having to open the .Rmd file.

I'm hoping to create one master file to do this for many markdown files in one go; which would save considerable time as you then don't have to open many markdown files and wait for each one to complete.

2 Answers

You are looking for rmarkdown::render().

Contents of "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)
```

Contents of script.R

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

A Way to Render Multiple Rmd

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

Thanks the-mad-statter, your answer was very helpful. The issue I faced, required me to prepare markdown dynamically. By adapting your code, that's easily possible:

Contents of "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
```

Contents of "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))
})

Like this you can create files with different text and different variables values in your code.

Related