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.