Verbatim code

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

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

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


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


alltt does not work but a simple


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: Logo

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: