Reputation: 1363
I have several R scripts that are are documented using #'
with the purpose of combining all the scripts into a single .Rmd
file.
I saw from this post that it's really straight forward to combine multiple .Rmd
files using code chunks within the master .Rmd
file
This is nice but I prefer to keep my code as .R
files because it runs faster for its intended purpose and the rendering of the documentation will not happen as often.
First I tried this in the main markdown file:
```{r, child = "script.R"}
```
But that didn't render properly - bascally a bunch of markdown text with the #'
s present.
Then I attempted to use what's described in this blog post in order to combine the R scripts in a single markdown file:
```{r}
library(rmarkdown)
rmarkdown::render("script.R")
```
But this just produces script.md
and does not embed the markdown into the main file. Any thoughts on how to correctly render the .R
scripts as markdown within the main file?
Upvotes: 3
Views: 1698
Reputation: 2922
This is my approach. It will use rmarkdown::render
to generate md file, and then read the content of the md file and incorporate it into the main file by setting the option results
to asis
. The drawback is the method generates some temporary files, and it may not be very performant but it achieves the goal.
---
title: "test"
author: "Consistency"
date: "2017/6/29"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
join <- function(ls, sep = ", "){
do.call(paste, append(ls, list(sep = sep)))
}
inline_render <- function(script_name){
suppressMessages(capture.output(rmarkdown::render(paste0(script_name, ".R"), output_format = "rmarkdown::md_document"), file = "tmp"))
cat(join(readLines(paste0(script_name, ".md")), "\n"))
}
```
```{r script, echo=FALSE, results='asis'}
inline_render("script")
```
```{r script1, echo=FALSE, results='asis'}
inline_render("script1")
```
Upvotes: 2