【问题标题】:Pretty tilde ~ from R chunk with knitr? [closed]漂亮的波浪号〜来自 R 块和 knitr? [关闭]
【发布时间】:2013-02-05 15:00:42
【问题描述】:

我希望在 LaTeX 中很好地显示代码块中的线性模型。模型调用采用带有波浪号的标准形式 ~ 在 LaTeX 中排版非常糟糕。

\documentclass{article}
\begin{document}
<<>>=
lm(Sepal.Width ~ Sepal.Length, data = iris)
@
\end{document}

代码编成knitr::knit(mwe.Rnw),然后通过PDFLaTeX运行。

在 LaTeX 中制作漂亮的波浪线非常烦人,让 knitr 制作波浪线似乎并不容易,更容易。对knit 生成的 .tex 文件的检查表明,代码被置于三个环境中,其中\begin{alltt} ... \end{alltt} 是有趣的一个。但是alltt 包没有提供任何对特殊字符的特殊排版的快速修复。

【问题讨论】:

    标签: r latex knitr pdflatex typesetting


    【解决方案1】:

    此解决方案的灵感来自 yihui's example on hooksthis post 和我的好友 RJ。

    \documentclass{article}
    \usepackage{xspace}
    \newcommand{\mytilde}{\lower.80ex\hbox{\char`\~}\xspace}
    \begin{document}
    <<setup, include=FALSE>>=
    library(knitr)
    hook_source = knit_hooks$get('source')
    knit_hooks$set(source = function(x, options) {
      txt = hook_source(x, options)
      # extend the default source hook
      gsub('~', '\\\\mytilde', txt)
    })
    @
    <<results = "hide">>=
    lm(Sepal.Width ~ Sepal.Length, data = iris)
    @
    \end{document}
    

    它还定义了一般使用的\mytilde 命令。例如,R 代码的内联示例:“in the form \texttt{response~\mytilde~predictors} ...”。

    xspace 不是绝对必要的(只要您删除新命令中的xspace),但会使命令更好用。

    【讨论】:

    • 这适用于回显代码,但波浪号在结果中仍然“难看”。
    • lm() 被包裹在summary() 中时,对我不起作用。通过设置echo=TRUE,我可以看到代字号在模型调用中正确显示,但不在摘要中,模型也显示为代字号,但被提升并且看起来错误。
    猜你喜欢
    • 2019-04-09
    • 2020-05-08
    • 2020-08-13
    • 2011-09-09
    • 2017-11-10
    • 2019-05-17
    • 1970-01-01
    • 2020-10-10
    • 2018-02-27
    相关资源
    最近更新 更多