How to write R script into Rmd as functioning code chunk?

You may be interested in the knitr function spin_child(). It can be used to insert R scripts as if they were code chunks in an R Markdown file.

To demonstrate, I created an R script called analysis.R that contained:

plot(rnorm(100))

And a template R Markdown file that contained:

---
title: "Insert R as Code Chunk"
output: html_document
---

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

`r knitr::spin_child("analysis.R")`

When I knit the file to HTML, the code in the R script appears as if it was a chunk in the R Markdown file: