4

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

Hugh
  • 2,374
  • 17
  • 30
  • 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: http://tex.stackexchange.com/questions/312/correctly-typesetting-a-tilde – 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
  • 1
    ... but an awkward one. The tilde is raised and smaller than normal. – Hugh Jun 24 '13 at 13:50

1 Answers1

3

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

Andrew Swann
  • 95,762