2013-02-05 80 views
6

我在代碼塊中有一個線性模型,我想在LaTeX中很好地顯示。模型調用採用帶有波形符號的標準形式,該形式在LaTeX中被嚴重排版。漂亮的波浪〜從R塊與knitr?

\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不提供任何特殊字符的特殊排版快速修復。

回答

7

此解決方案受yihui's example on hooks,this 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),但使命令更好使用。

+0

這適用於回顯代碼,但代字號在結果中仍然是「醜陋的」。 –