elisa elisa - 20 days ago 5
Markdown Question

Preserve markdown in chunked file for knitr

I have an R script called

runDataAnalysis.R
, in which I have a call to a long analysis file
actualAnalysis.R
.

I want to generate a report with
knitr
(I'm not using RStudio).

So I followed some good advice and did the following:

I have
## @knitr runMostAnalyses
at the top of my long analysis file.

I also have these lines in my
runDataAnalysis.R
file:

---
output: html_document:
toc: true
---

```{r echo=FALSE}
read_chunk('pathtofile/actualAnalysis.R')
```

```{r first}
<<runMostAnalyses>>
```


Finally, I run it and get the report by calling
rmarkdown::render('runDataAnalysis.R')
. This works for the most part but it doesn't preserve the markdown indicated in the sourced file (at least not in the same format as it usually works for rmarkdown). For example, I have different title levels with
#' #
,
#' ##
and
#' ###
. But this just gets copied verbatim in the report file and not interpreted as titles (and included in the table of contents). I couldn't find any relevant option for this in the chunk options.

Is the syntax different or am I doing something wrong when evaluating the chunk?

Answer

If you import Rmd into Rmd files, you can use one of the solutions described here: either using the chunk parameter child

```{r, child = 'pathtofile/actualAnalysis.R'}
```

or using the function knit_child (which returns the converted document as a string) together with the chunk parameter results set to 'asis':

```{r echo=FALSE, results='asis'}
   cat(knit_child(text = readLines('pathtofile/actualAnalysis.Rmd', quiet = TRUE)) 
```

If the imported files are formatted R scripts to be processed with spin, the same should work after replacing knit_child by spin_child.

If the parent document itself was also such a formatted R script to be processed with spin (not an Rmd, as in your example), you could import child documents (formatted for spin) using double curly braces, as described in the spin_child documentation:

{{ spin_child('pathtofile/actualAnalysis.R') }}