【问题标题】:Unevaluated inline code with formula using \Sexpr{} in knitr在 knitr 中使用 \Sexpr{} 的公式未计算的内联代码
【发布时间】:2017-11-03 16:20:02
【问题描述】:

我喜欢将\Sexpr{''} 用于内联 R 代码,包括突出显示。但是,这似乎不适用于公式。波浪号似乎是个问题。它只是没有显示在 pdf 中。

这是一个最小的例子:

\documentclass{article}
\begin{document}

<<setup, echo=FALSE>>=
library("knitr")

knit_hooks$set(inline = function(x) { 
  if (is.numeric(x)) return(knitr:::format_sci(x, 'latex')) 
  highr:::hi_latex(x) 
}) 
@

\Sexpr{'plot(x, y)'} works.

\Sexpr{'lm(response ~ treatment, data)'} does not show the tilde.

\end{document}

我得到的是以下内容:

感谢任何帮助。

【问题讨论】:

    标签: r latex knitr


    【解决方案1】:

    仔细查看你在 setup 中定义的内联函数的结果:

    inline('lm(response ~ treatment, data)')
    
    "[1]  \\hlkwd{lm}\\hlstd{(response} \\hlopt{~} \\hlstd{treatment, data)}"
    

    这里有两个问题:波浪号被标记为 \hlopt{} 而不是 \hlstd{},并且它没有被正确地标记为 LaTeX 的符号。为此,您需要将其插入为\textasciitilde

    我不知道是否有办法修改highr::hi_latex 以正确解释所有数学符号,如波浪号。除此之外,您可以如下修改 LaTeX 输出 事后

    <<setup, echo=FALSE, message=FALSE>>=
    library(knitr)
    library(dplyr)
    library(stringr)
    
    knit_hooks$set(inline = function(x) { 
      if (is.numeric(x)) return(knitr:::format_sci(x, 'latex')) 
      highr:::hi_latex(x) %>% 
        str_replace("~", "\\\\textasciitilde") %>% 
        str_replace("hlopt", "hlstd")
      }) 
    @
    

    【讨论】:

    • 我最终做的是使用highr:::hi_latex(x) %&gt;% str_replace("hlopt", "textalltt")here 的textalltt 定义。这最终完全符合我的期望。你的帮助肯定让我到了那里。谢谢!
    猜你喜欢
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 2013-09-09
    • 2015-12-18
    相关资源
    最近更新 更多