# Tilde in verbatim

I am writing a manual for an R file in which expressions like this are common:

lm.1 <- lm(y ~ x1 + x2)


I will be enclosing code samples in a verbatim environment but this doesn't work properly for tildes.

To create the above in single line through LaTeX is quite simple

$\mathtt{lm.1}\; \verb"<-" \;\mathtt{lm(y \sim x1+x2)}.$


but creating such a line for each instance of the code where a tilde occurs in that line seems inefficient.

There are ways to propsectively define tildes, but my code is already written. What is the best way to make tildes appear as they do in the R file (or in Notepad etc)?

• I'm at a loss as to what you want to accomplish. What do you mean with What is the best way to make tildes appear as they do in the R file (or in Notepad etc)?? I'm thinking the problem is that \sim produces the wrong type of tilde for you. If so look at this question: tex.stackexchange.com/questions/312/… – Mythio Jun 24 '13 at 13:04
• Well, the problem is that I will be enclosing the code in a verbatim environment where \sim won't have the desired result. Is there a more efficient way to produce the tilde symbol as displayed in notepad than going through and replacing each instance of ~ (and remembering to do so in future versions)? – Hugh Jun 24 '13 at 13:09
• ~ produces a ~ in verbatim mode! – Ian Thompson Jun 24 '13 at 13:48
• ... but an awkward one. The tilde is raised and smaller than normal. – Hugh Jun 24 '13 at 13:50

I suggest you use the listings package as follows:

\documentclass{article}

\usepackage[formats]{listings}

\lstdefineformat{R}{~=$$\sim$$}
\lstset{basicstyle=\ttfamily,format=R}

\begin{document}

\begin{lstlisting}
lm.1 <- lm(y ~ x1 + x2)
\end{lstlisting}

\end{document}


The option formats provides a mechanism to substitute certain characters by other code. Here we set up an R format where ~ is replaced by \sim in math mode. Using lstset this style is set for all listings; you could instead add these options to individual code listings or define a specific style via lstdefinestyle{myR}{basicstyle=\ttfamily,format=R} to be used as \begin{listing}[style=myR] ... \end{listing}.

• I guess literate={~}{$\sim$}{1} would also work. – Werner Jun 24 '13 at 13:56
• @Werner Yes that works too. Why is that section of the manual not about Literate Programming? – Andrew Swann Jun 24 '13 at 13:59
• This appears to solve the problem! Thank you. As an addendum: the text so produced within the lstlisting environment appears to be a lot more expanded. How can I compress the printed text? – Hugh Jun 24 '13 at 14:03
• See the columns option – daleif Jun 24 '13 at 14:10
• Try the options columns=fixed,basewidth=0.5em. By default listings uses a flexible column formatting approach. – Andrew Swann Jun 24 '13 at 14:15