Pretty tilde ~ from piece R with a knife?

I have a linear model in a code block that I want to display well in LaTeX. The model call takes a standard form with a tilde ~, which is terribly typed in LaTeX.

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

The code is knitted by knitr::knit(mwe.Rnw) and then executed via PDFLaTeX.

Creating nice tildes is very annoying in LaTeX, and getting knitr to make them seems not quite easy, simpler. Checking the .tex file created by knit shows that the code fits into three environments, of which \begin{alltt} ... \end{alltt} is interesting. But the alltt package alltt not offer quick fixes for a special set of special characters.

+6
source share
1 answer

This decision is inspired by the yihui hook example , this post and my buddy 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} 

It also defines the \mytilde for general use. For example, an example R-code line: " in the form \texttt{response~\mytilde~predictors} ... ".

The xspace package xspace not strictly necessary (if you remove xspace in a new command), but makes the command more enjoyable to use.

+7
source

All Articles