【问题标题】:extract R code from template using knit_expand()使用 knit_expand() 从模板中提取 R 代码
【发布时间】:2017-06-20 14:36:09
【问题描述】:

我使用knitr 生成了一个动态文档。该文件使 广泛使用包的knit_expand() 函数 模板。这是由 MWE 说明的(基于谢一辉自己的 example 函数)。

  • 主文档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.Rnw

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

我现在需要提取相应的 R 代码。运行purl("knit-expand-MWE.Rnw") 输出knit-expand-MWE.R,其中包括块中的代码以及对模板的引用:

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

我想要的是相应的“扩展”代码(为了不使用knitr的同事的利益),例如:

## ----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, ]

我怎样才能做到这一点?

【问题讨论】:

    标签: r knitr dynamic-reports reproducible-research


    【解决方案1】:

    您可以在src 上运行purl(),例如。 g.

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

    【讨论】:

    • 在 MWE 中,将那行代码放在 run-all 块的底部就可以了。但是,如果该块位于主文档调用的子文档中,则编译会因以下错误而窒息:## Error in parse block(g[-1], g[1], params.src): duplicate label ’row-1’。有没有办法解决这个问题?
    • 我不太确定这个错误在这种情况下是否有意义,但您可以通过设置options(knitr.duplicate.label = 'allow') 来抑制它。
    • 相信问题是knit_child()purl() 都有效地在src 上调用knit(),这会导致标签重复(没有重复否则标签)。因此,您在上面建议的选项可以解决问题。谢谢一辉!
    • 你说得对,purl()本质上是调用knit(),导致标签重复的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 2018-12-02
    • 2021-12-16
    • 2016-03-03
    • 2016-11-10
    相关资源
    最近更新 更多