7

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.

dynamo
  • 2,988
  • 5
  • 27
  • 35

1 Answers1

8

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.

Community
  • 1
  • 1
dynamo
  • 2,988
  • 5
  • 27
  • 35
  • This works well for the echoed code, but the tilde is still "ugly" in the results. – han-tyumi May 27 '17 at 14:48
  • didn't work for me when ``lm()`` was wrapped inside ``summary()``. By setting ``echo=TRUE`` I could see that the tilde displayed properly in the model call, but not inside the summary, where the model is also displayed with a tilde, but is raised and looks wrong. – PatrickT Apr 22 '18 at 00:51