很漂亮〜来自R chunk with knitr?

时间:2013-02-05 15:00:43

标签: r latex knitr pdflatex typesetting

我在代码块中有一个线性模型,我希望在LaTeX中很好地显示。模型调用采用标准形式,使用波浪线〜在LaTeX中可以进行排版。

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

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

在LaTeX中制作漂亮的波浪线非常烦人,并且让它们变得简单,更容易。对knit生成的.tex文件的检查表明代码被放入三个环境中,其中\begin{alltt} ... \end{alltt}是有趣的环境。但是alltt包不能为特殊字符的特殊排版提供任何快速修复。

1 个答案:

答案 0 :(得分:7)

此解决方案的灵感来自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不是严格必要的(只要删除new命令中的xspace),但使命令更好用。