Verbatim code

When rendering computer code and output in LateX, I usually resort to the basic verbatim environment, as in

\begin{verbatim}
> matrix(1:4,ncol=3)
[,1] [,2] [,3]
[1,]    1    3    1
[2,]    2    4    2
Warning message:
data length [4] is not a submultiple or multiple of the number of columns [3] in matrix in: matrix(1:4, ncol = 3)
\end{verbatim}

However, I do not like the way tildes are represented in this environment, being considered as accents rather than standard characters, as in the R command

lm(y~x)

Asking Springer-Verlag TeXperts for help during my last round of corrections of Introducing Monte Carlo Methods with R before it left for the printer, I received a solution which is to use the alltt environment instead, which allows for LaTeX commands within the verbatim rendering, using \(\sim\) instead of ~. (I have been looking for this solution for ages and of course, provided with the solution of using alltt instead, I immediately found a lot of related posts!) There is a drag, though, which is that curly brackets {} vanish from the R code, unless replaced with the LaTeX versions \(\{\) and \(\}\).

When ~is used in the in-line rendering

\verb+lm(y~x)+

alltt does not work but a simple

\verb+lm(y+$\sim$\verb+x)+

is sufficient.

2 Responses to “Verbatim code”

  1. Thanks, Darren, this sounds even better!

  2. Try the “listings” package for verbatim code – it does highlighting, optional line numbers, etc. It doesn’t know about R, but you can tell it. Something like the following is fine:

    \lstset{language=R, basicstyle =\ttfamily\small, showspaces=false, showtabs=false, showstringspaces=false, literate= {~} {$\sim$}{2}}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 603 other followers