【问题标题】:Knitr asis not working with output from hooksKnitr asis 不适用于钩子的输出
【发布时间】:2014-09-10 19:33:56
【问题描述】:

在 Rnw/LaTeX 中,对来自 knitr hooks 的通用输出的一种使用可能是用一些花哨的环境来装饰来自块的数据。
例如,特定于块的代码可以为表生成核心数据,并且在提供重复修饰之前和之后的钩子代码。

考虑以下 sn-p:

\documentclass{article}
\begin{document}

<<myhooks,  include=FALSE>>=
printhook=function(before, options, envir) {
    if (before) {

        return('\nCommon R \\LaTeX\\ in before-hook')
    } else {
        return('\nCommon R \\LaTeX\\ in after-hook')
    }
}

knit_hooks$set(lprint = printhook)

@ 


<<test, results='asis', lprint=TRUE,  echo=FALSE>>=
cat("R \\LaTeX\\ in current chunk\n")
@ 

\end{document}

问题在于 LaTeX 输出大致如下:

   \begin{kframe}
   Common R \LaTeX\ in before-hook
   \end{kframe}

   R \LaTeX\ in current chunk

   \begin{kframe}
   Common R \LaTeX\ in after-hook
   \end{kframe}

钩子代码实际上并不是asis,而是被包裹在kframe 环境中,这可以防止将三个部分粘合在一起。

我们如何删除封闭的kframe

【问题讨论】:

    标签: r templates latex knitr rnw


    【解决方案1】:

    对于这个问题,我没有一个优雅的解决方案。以下是一种可能的解决方案。基本思路是将输出钩子chunk替换为results == 'asis',不回显源代码,代码块中不产生绘图:

    \documentclass{article}
    \begin{document}
    
    <<myhooks, include=FALSE>>=
    local({
      hook_chunk = knit_hooks$get('chunk')
      knit_hooks$set(chunk = function(x, options) {
        x = hook_chunk(x, options)
        if (options$results == 'asis' && !options$echo && options$fig.num == 0) {
          # remove all kframe's
          gsub('\\\\(begin|end)\\{kframe\\}', '', x)
        } else x
      })
    })
    printhook=function(before, options, envir) {
        if (before) {
            return('\nCommon R \\LaTeX\\ in before-hook')
        } else {
            return('\nCommon R \\LaTeX\\ in after-hook')
        }
    }
    knit_hooks$set(lprint = printhook)
    @
    
    <<test, results='asis', lprint=TRUE,  echo=FALSE>>=
    cat("R \\LaTeX\\ in current chunk\n")
    @
    
    \end{document}
    

    【讨论】:

    • +1 谢谢,它解决了问题。我意识到这是一个共同的需求:yihui.name/knitr/hooks#comment-1339608701。希望直接从单个块挂钩绕过 kframe 的可能性将成为即将发布的 knitr 版本中的一个功能。
    猜你喜欢
    • 2019-12-25
    • 1970-01-01
    • 2017-02-04
    • 2020-08-28
    • 2016-10-17
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    相关资源
    最近更新 更多