I have a linear model in a code chunk that I want to display nicely in LaTeX. The model call takes the standard form with a tilde ~ which gets typeset horribly in LaTeX.
\documentclass{article}
\begin{document}
<<>>=
lm(Sepal.Width ~ Sepal.Length, data = iris)
@
\end{document}
The code is knitted knitr::knit(mwe.Rnw)
and then run through PDFLaTeX.
Making nice tildes is very annoying in LaTeX and getting knitr to make them doesn't seem entirely easy, easier. An inspection of the .tex file produced by knit
shows that the code is put into three environments, of which \begin{alltt} ... \end{alltt}
is the interesting one. But the package alltt
doesn't offer any quick fixes for special typesetting of special characters.
This solution is inspired by yihui's example on hooks, 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
command for general use. For example, in-line examples of R code: "in the form \texttt{response~\mytilde~predictors} ...
".
The package xspace
is not strictly neccessary (as long as you remove the xspace
in the newcommand), but makes the command nicer to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With