Extract R code from a template using knit_expand ()

I created a dynamic document using knitr. The document makes extensive use of the package knit_expand()for templates. This is illustrated by MWE (based on the Yihui Xie example for a 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}
    
  • The template template.Rnwcalled by the 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}}, ]
    @
    

Now I need to extract the corresponding R code. Execution of purl("knit-expand-MWE.Rnw")outputs knit-expand-MWE.R, which includes code in a piece with a link to a template:

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

Instead, I need the appropriate β€œadvanced” code (for colleagues who don’t 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?

+4
1

purl() src, e. .

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

Source: https://habr.com/ru/post/1679729/


All Articles