jrcalabrese
jrcalabrese

Reputation: 2321

Run RMarkdown (.rmd) from inside another .rmd without creating HTML output

I am making my code more modular and would like to run multiple RMarkdown files from one overall RMarkdown. I believe I could do this if I translated all my RMarkdown files to .R scripts and used source(), but I like the document-like nature of RMarkdown and I can describe what I'm doing as I'm doing it in plain text.

The goal is to wrangle data and export a usable .sav file. I want to run clean.rmd from run.rmd, but I don't want any HTML/pdf/etc. output. Removing the output line in the YAML header doesn't prevent output. If there is a way to do this without translating everything to .R scripts, I would be very appreciative. Thank you.

clean.rmd: Script that does the cleaning

---
title: "clean"
author: "jrcalabrese"
date: "12/30/2021"
output: html_document
---

```{r}
library(tidyverse)
library(haven)
```

```{r}
data(cars)
cars <- cars %>%
  mutate(newvar = speed + dist)
```

```{r}
write_spss(cars, "~/Documents/cars_new.sav", compress = FALSE)
```

run.rmd: Script that runs clean.rmd

---
title: "run"
author: "jrcalabrese"
date: "12/30/2021"
output: html_document
---

```{r}
rmarkdown::render("~/Documents/clean.rmd")
```

Upvotes: 3

Views: 2421

Answers (1)

jrcalabrese
jrcalabrese

Reputation: 2321

Thank you for your help! This function works:

---
title: "run"
author: "jrcalabrese"
date: "12/30/2021"
#output: html_document
---

```{r}
source_rmd = function(file, ...) {
  tmp_file = tempfile(fileext=".R")
  on.exit(unlink(tmp_file), add = TRUE)
  knitr::purl(file, output=tmp_file)
  source(file = tmp_file, ...)
}
```

```{r}
source_rmd("~/Documents/clean.rmd")
```

Upvotes: 4

Related Questions