[Tex/LaTex] Tilde in verbatim

tildeverbatim

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)?

Best Answer

I suggest you use the listings package as follows:

Sample output

\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}.

Related Question