How to Call External R Script from R Markdown (.Rmd) in Rstudio

Include code from an external R script, run in, display both code and output

Although the accepted answer provides a simple and working solution, I think the most idiomatic way of doing this (without having to modify the external script at all) is to use the chunk option code to set the contents of external.R as chunk code:

```{r, code = readLines("external.R")}
```

Include R script with markdown tags as external file in Rmarkdown file

I'm not totally sure if I understand your question, but it sounds to me that you were looking for knitr::spin_child(), which converts an R script to Rmd and knit it as a child document:

```{r}
knitr::spin_child('tmp.R')
```

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

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)

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

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

Source code from Rmd file within another Rmd

After some further searching, I've found a solution. There is a package option in knitr that can be set to change the behavior for handling duplicate chunks, appending a number after their label rather than failing with an error. See https://github.com/yihui/knitr/issues/957.

To set this option, use options(knitr.duplicate.label = 'allow').

For the sake of completeness, the full code for the function I've written is

source_rmd <- function(file, local = FALSE, ...){
options(knitr.duplicate.label = 'allow')

tempR <- tempfile(tmpdir = ".", fileext = ".R")
on.exit(unlink(tempR))
knitr::purl(file, output=tempR, quiet = TRUE)

envir <- globalenv()
source(tempR, local = envir, ...)
}

Passing R markdown parameters to a sourced R script

Have a look at the argument local in source (?source).

local TRUE, FALSE or an environment, determining where the parsed expressions are evaluated. FALSE (the default) corresponds to the user's workspace (the global environment) and TRUE to the environment from which source is called.

When rendering the Rmd directly, the params are the ones set by default, and you are in the global environment. So this will work:

---
params:
pathogen:
label: "Enter pathogen of interest:"
value: Shigella
input: select
choices: [Campylobacter, Escherichia, Salmonella, Shigella]
pkginstall:
value: no
title: "Pathogen Report"
date: "`r format(Sys.time(), '%d %B %Y')`"
output: html_document
---

```{r GDW Query, echo=TRUE, cache=FALSE, message=FALSE, warning=FALSE, results='hide'}
####################################################################
# QUERY DATABASE AND EXTRACT DATA
source(Extract_data.R, local=FALSE) # same as source(Extract_data.R)

However, when running the Rmd through a Shiny App you want to work in the environment that Shiny works in, and you want to source the external script as if it was pasted in line (see https://shiny.rstudio.com/articles/scoping.html). The following should work:

---
params:
pathogen:
label: "Enter pathogen of interest:"
value: Shigella
input: select
choices: [Campylobacter, Escherichia, Salmonella, Shigella]
pkginstall:
value: no
title: "Pathogen Report"
date: "`r format(Sys.time(), '%d %B %Y')`"
output: html_document
---

```{r GDW Query, echo=TRUE, cache=FALSE, message=FALSE, warning=FALSE, results='hide'}
####################################################################
# QUERY DATABASE AND EXTRACT DATA
source(Extract_data.R, local=TRUE)


Related Topics



Leave a reply



Submit