Skip to content

How to nicely display R code with the LaTeX package 'listings'?

6 messages · Marius Hofert, Frank E Harrell Jr, Yihui Xie +1 more

#
Dear expeRts,

What's a 'good' (nice-looking, easy-to-read) setup for the LaTeX package
'listings' to display R code?

The two versions below are partly inspired by the settings of the package
SweaveListingUtils and
http://r.789695.n4.nabble.com/R-How-to-format-R-code-in-LaTex-documents-td816055.html

Any suggestions, comments, or improvements are welcome.

Cheers,

Marius

### Version 1 ##################################################################

\documentclass{scrartcl}

\usepackage[T1]{fontenc}
\usepackage[american]{babel}

\usepackage{graphicx}
\usepackage{fancyvrb}
\usepackage{listings}

\lstset{% setup listings
	language=R,% set programming language
	basicstyle=\small,% basic font style
	keywordstyle=\bfseries,% keyword style
        commentstyle=\ttfamily\itshape,% comment style
	numbers=left,% display line numbers on the left side
	numberstyle=\scriptsize,% use small line numbers
	numbersep=10pt,% space between line numbers and code
	tabsize=3,% sizes of tabs
	showstringspaces=false,% do not replace spaces in strings by a certain character
	captionpos=b,% positioning of the caption below
        breaklines=true,% automatic line breaking
        escapeinside={(*}{*)},% escaping to LaTeX
        fancyvrb=true,% verbatim code is typset by listings
        extendedchars=false,% prohibit extended chars (chars of codes 128--255)
        literate={"}{{\texttt{"}}}1{<-}{{$\leftarrow$}}1{<<-}{{$\twoheadleftarrow$}}1
        {~}{{$\sim$}}1{<=}{{$\le$}}1{>=}{{$\ge$}}1{!=}{{$\neq$}}1{^}{{$^\wedge$}}1,% item to replace, text, length of chars
        alsoletter={.<-},% becomes a letter
        alsoother={$},% becomes other
        otherkeywords={!=, ~, $, *, \&, \%/\%, \%*\%, \%\%, <-, <<-, /},% other keywords
        deletekeywords={c}% remove keywords
}

\begin{document}

\noindent Just some text; see Line \ref{foo}.
\begin{lstlisting}[caption={A first example}, label=list:ex]
x <- c(1, 3, 2)
id <- function(x){
    x # just a dummy (*\label{foo}*)
}
3 <= 4
3 != 4
!TRUE
y <- "foo"
(pv <- sum(x*x^x))
y ~ x + a
\end{lstlisting}

\end{document}


### Version 2 ##################################################################

\documentclass{scrartcl}

\usepackage[T1]{fontenc}
\usepackage[american]{babel}

\usepackage{graphicx}
\usepackage{fancyvrb}
\usepackage{listings}
\usepackage{bm}
\usepackage{xcolor}

\xdefinecolor{gray}{rgb}{0.4,0.4,0.4}
\xdefinecolor{blue}{RGB}{58,95,205}% R's royalblue3; #3A5FCD

\lstset{% setup listings
	language=R,% set programming language
	basicstyle=\ttfamily\small,% basic font style
	keywordstyle=\color{blue},% keyword style
        commentstyle=\color{gray},% comment style
	numbers=left,% display line numbers on the left side
	numberstyle=\scriptsize,% use small line numbers
	numbersep=10pt,% space between line numbers and code
	tabsize=3,% sizes of tabs
	showstringspaces=false,% do not replace spaces in strings by a certain character
	captionpos=b,% positioning of the caption below
        breaklines=true,% automatic line breaking
        escapeinside={(*}{*)},% escaping to LaTeX
        fancyvrb=true,% verbatim code is typset by listings
        extendedchars=false,% prohibit extended chars (chars of codes 128--255)
        literate={"}{{\texttt{"}}}1{<-}{{$\bm\leftarrow$}}1{<<-}{{$\bm\twoheadleftarrow$}}1
        {~}{{$\bm\sim$}}1{<=}{{$\bm\le$}}1{>=}{{$\bm\ge$}}1{!=}{{$\bm\neq$}}1{^}{{$^{\bm\wedge}$}}1,% item to replace, text, length of chars
        alsoletter={.<-},% becomes a letter
        alsoother={$},% becomes other
        otherkeywords={!=, ~, $, \&, \%/\%, \%*\%, \%\%, <-, <<-, /},% other keywords
        deletekeywords={c}% remove keywords
}

\begin{document}

\noindent Just some text; see Line \ref{foo}.
\begin{lstlisting}[caption={A first example}, label=list:ex]
x <- c(1, 3, 2)
id <- function(x){
    x # just a dummy (*\label{foo}*)
}
3 <= 4
3 != 4
!TRUE
y <- "foo"
(pv <- sum(x*x^x))
y ~ x + a
\end{lstlisting}

\end{document}
#
The knitr package makes this relatively easy to do.  See for example
http://biostat.mc.vanderbilt.edu/KnitrHowto

Frank


Marius Hofert-3 wrote

            
-----
Frank Harrell
Department of Biostatistics, Vanderbilt University
--
View this message in context: http://r.789695.n4.nabble.com/How-to-nicely-display-R-code-with-the-LaTeX-package-listings-tp4648110p4648149.html
Sent from the R help mailing list archive at Nabble.com.
#
Or see https://github.com/yihui/knitr-examples/blob/master/015-listings.Rnw
for a minimal example.

Regards,
Yihui
--
Yihui Xie <xieyihui at gmail.com>
Phone: 515-294-2465 Web: http://yihui.name
Department of Statistics, Iowa State University
2215 Snedecor Hall, Ames, IA
On Thu, Nov 1, 2012 at 1:23 PM, Frank Harrell <f.harrell at vanderbilt.edu> wrote:
#
Dear Yihui, Dear Frank,

Thanks for helping.

I am aware of Sweave and knitr and this is an incredible development. Still,
this "machinery" is too heavy for my needs. I typically use pure R scripts for
my work (well documented with Roxygen). I can then easily debug and
are not disturbed by additional text already. Also, I can easily run a pure R
script on a computer cluster (not sure about an .Rnw -- okay, one might use a
makefile that first tangles it and then sends the script to the cluster, but that
already adds another layer of complexity). Another thing is syncronization
(forward/backward search from .pdf). We recently managed to use Duncan's "patchDVI" to
get backward sync to the .Rnw file instead of the .tex file. This was even in a
multi-file document (several .Rnw loaded from a master file) where it is
extremely useful. But that was not so easy to set up (and I am not sure if knitr
does/can incorporate this). The biggest problem,
however, is portability. None of my co-authors (except for Martin) uses such
tools and is therefore able to compile the .Rnw document (they mostly use .tex
and can compile those documents). So for putting in some lines of code in a
paper, this is quite restrictive (that's why I was hoping for a latex-related
solution -- still asking on r-help since I'd expect R users to have encountered
this issue before).

Cheers,

Marius



Yihui Xie <xie at yihui.name> writes:
#
On Nov 1, 2012, at 12:57 PM, Marius Hofert wrote:

            
I use the Latex package "listings" with the following settings:

\lstset{ %
  language=R,                % the language of the code
  basicstyle=\footnotesize,           % the size of the fonts that are used for the code
  numbers=left,                   % where to put the line-numbers
  numberstyle=\tiny\color{gray},  % the style that is used for the line-numbers
  stepnumber=2,                   % the step between two line-numbers. If it's 1, each line 
                                  % will be numbered
  numbersep=5pt,                  % how far the line-numbers are from the code
  backgroundcolor=\color{white},      % choose the background color. You must add \usepackage{color}
  showspaces=false,               % show spaces adding particular underscores
  showstringspaces=false,         % underline spaces within strings
  showtabs=false,                 % show tabs within strings adding particular underscores
  frame=single,                   % adds a frame around the code
  rulecolor=\color{black},        % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. commens (green here))
  tabsize=2,                      % sets default tabsize to 2 spaces
  captionpos=b,                   % sets the caption-position to bottom
  breaklines=true,                % sets automatic line breaking
  breakatwhitespace=false,        % sets if automatic breaks should only happen at whitespace
  title=\lstname,                   % show the filename of files included with \lstinputlisting;
                                  % also try caption instead of title
  keywordstyle=\color{blue},          % keyword style
  commentstyle=\color{dkgreen},       % comment style
  stringstyle=\color{mauve},         % string literal style
  escapeinside={\%*}{*)},            % if you want to add a comment within your code
  morekeywords={*,...}               % if you want to add more keywords to the set
}



HTH,

-Roy M.
**********************
"The contents of this message do not reflect any position of the U.S. Government or NOAA."
**********************
Roy Mendelssohn
Supervisory Operations Research Analyst
NOAA/NMFS
Environmental Research Division
Southwest Fisheries Science Center
1352 Lighthouse Avenue
Pacific Grove, CA 93950-2097

e-mail: Roy.Mendelssohn at noaa.gov (Note new e-mail address)
voice: (831)-648-9029
fax: (831)-648-8440
www: http://www.pfeg.noaa.gov/

"Old age and treachery will overcome youth and skill."
"From those who have been given much, much will be expected" 
"the arc of the moral universe is long, but it bends toward justice" -MLK Jr.
#
Hi Marius,

I'm not sure if this helps:

1. knitr::spin() can convert a roxygen script to a report, although it
has no support to any roxygen @tags, e.g.
https://github.com/yihui/knitr/blob/master/inst/examples/knitr-spin.R
In your case, you can spin('code.R', format = 'Rnw')

2. knitr does have concordance support (opts_knit$set(concordance =
TRUE)) like Sweave, although not as accurate as it; RStudio makes use
of the concordance information generated by knitr to support
synchronization; I have not tried patchDVI yet, but I guess it should
work the same for knitr since knitr writes the same concordance file
as Sweave.

3. I do not think it matters if your collaborators do not use Sweave
or knitr, because you can always \input{} your work into their LaTeX
documents. I mean you can separate the R part from the rest of of the
LaTeX document and compile your child document separately; that is
where knitr may be helpful.

Regards,
Yihui
--
Yihui Xie <xieyihui at gmail.com>
Phone: 515-294-2465 Web: http://yihui.name
Department of Statistics, Iowa State University
2215 Snedecor Hall, Ames, IA


On Thu, Nov 1, 2012 at 2:57 PM, Marius Hofert
<marius.hofert at math.ethz.ch> wrote: