Search code examples
rknitrdynamic-reportsreproducible-research

extract R code from template using knit_expand()


I have produced a dynamic document using knitr. The document makes extensive use of the package's knit_expand() function for templates. This is illustrated by the MWE (based on Yihui Xie's own example for the function).

  • Main document knit-expand-MWE.Rnw

    \documentclass{article}
    
    \title{How to extract code when using\\
    knit\_expand() for templates?}%
    \author{Knitr User}
    
    \begin{document}
    
    \maketitle
    \tableofcontents
    
    \newpage
    \section{Write one row of data}
    
    Only the first two sections are evaluated.
    
    <<run-all, include=FALSE>>=
    library(knitr)
    src = NULL
    for (i in 1:3) src = c(src, knit_expand('template.Rnw'))
    @
    
    \Sexpr{paste(knit(text = src), collapse = '\n')}
    
    \end{document}
    
  • Template template.Rnw called by main document

    \subsection{Now i is {{i}}}
    
    This chunk is {{if (i > 2) 'not '}}evaluated.
    <<row-{{i}}, eval={{i <= 2}}>>=
    # row number {{i}}
    iris[{{i}}, ]
    @
    

I now need to extract the corresponding R code. Running purl("knit-expand-MWE.Rnw") outputs knit-expand-MWE.R, which includes the code in the chunk with a reference to the template:

## ----run-all, include=FALSE----------------------------------------------
library(knitr)
src = NULL
for (i in 1:3) src = c(src, knit_expand('template.Rnw'))

What I would like instead is the corresponding "expanded" code (for the benefit of colleagues who do not use knitr), for example:

## ----row-1, eval=TRUE----------------------------------------------
## row number 1
iris[1, ]

## ----row-2, eval=TRUE----------------------------------------------
## row number 2
iris[2, ]

## ----row-3, eval=FALSE----------------------------------------------
## row number 3
iris[3, ]

How can I achieve this?


Solution

  • You can run purl() on src, e. g.

    purl(text = src, output = 'knit-expand.R')