Serving multiple R scripts as markdown in one markup file

I have several R scripts that are documented with the #'

goal of combining all scripts into one file .Rmd

.

I saw from this post that it does indeed concatenate multiple files directly .Rmd

using chunks of code in the main .Rmd

file

This is fine, but I prefer to have my code .R

because it works faster as intended and the rendering of the documentation won't happen as often.

I first tried this in the main markdown file:

```{r, child = "script.R"}
```

      

But it didn't display properly - basically a bunch of markdown text with present #'

.

Then I tried to use what is described in this blog post to combine R scripts into one markup file:

```{r}
library(rmarkdown)
rmarkdown::render("script.R")
```

      

But that just creates script.md

and doesn't insert the markdown into the main file. Any thoughts on how to properly render the scripts .R

as markdown in the main file?

+3


source to share


1 answer


This is my approach. It will use rmarkdown::render

to generate the md file and then read the contents of the md file and include it in the main file by setting the option results

to asis

. The disadvantage is that the method generates some temporary files and it may not be very efficient, but it does the trick.



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

      

+2


source







All Articles