【问题标题】:Conditional output of dynamic text in a LaTeX knitr documentLaTeX knitr 文档中动态文本的条件输出
【发布时间】:2017-08-04 00:59:20
【问题描述】:

我想在 knitr LaTeX 文档 (.Rnw) 中打印几句话,但前提是存在某些数据。这些句子大多是文本,但也有一些 R。

例子:

A chi-squared test of your observed sizes has a p-value of
\Sexpr{format(calculated_chisq$p.value,digits=3,scientific=F)}.
A p-value below 0.05 means you should be concerned that your
groups are broken.  The lower the p-value, the more worried you
should be.

我用results='asis' 尝试了一个块,但我认为该块被解释为 R。

我用 R 尝试了 print() 和 paste()。它很难看,但它有效。但是,它会在其中添加似乎与 R 提示符相对应的额外文本。

有什么好的方法吗?

This 是相关的,但不同。 This 是一样的,但没有得到答复。

【问题讨论】:

    标签: r latex knitr rnw


    【解决方案1】:

    这个问题与that question 密切相关,但我认为不是重复的:那里接受的答案转化为一个丑陋的\Sexp 怪物,里面有一个条件。代码既不好读也不好写。

    My own answer 也不适用,因为 1) asis 引擎不允许在文本中使用动态元素,以及 2) 因为来自 asis 的输出在 RNW 文档中的背景颜色为灰色。

    我建议以下解决方案:

    \documentclass{article}
    \begin{document}
    
    <<>>=
      x <- rnorm(1)
    @
    
    The value of $x$ is \Sexpr{x}.
    
    <<echo=FALSE, results = "asis">>=
      pattern <- "This will only be displayed if $x$ is positive. The value of $x$ is %.2f."
      if (x > 0) cat(sprintf(pattern, x))
    @
    
    \end{document}
    

    条件输出易于读写(pattern),动态元素通过sprintf插入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 2016-08-29
      • 2015-12-30
      • 1970-01-01
      相关资源
      最近更新 更多