Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty tilde ~ from R chunk with knitr? [closed]

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.

like image 719
dynamo Avatar asked Feb 05 '13 15:02

dynamo


1 Answers

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.

like image 55
dynamo Avatar answered Nov 03 '22 14:11

dynamo