Highlighting R code in LaTeX using SweaveListingUtils

It is well known that you can use Sweave to integrate R code into a LaTeX document. However, how do we highlight R code in LaTeX? LaTeX got its own powerful package listings that can highlight source code from various languages. Moreover, the package SweaveListingUtils provides utilities for defining R as a listings “language”. To highlight your R code in your Sweave document you have to include the following code chunk:

\RequirePackage{listings}
\RequirePackage{Sweave}

\begin{Scode}{label=SweaveListingsPreparations , results=tex , echo=FALSE}
require(SweaveListingUtils)
SweaveListingOptions(Rcolor=c(0,0,0), overwrite=TRUE,
    Keywordstyle="{\\footnotesize\\color{blue}}",
    interm.Keywordstyle="{\\footnotesize\\color{blue}}",
    Rset=list("fancyvrb" = "true", "language" = "R", "escapechar" = "`",
        "basicstyle" = "{\\footnotesize\\color{Rcolor}}",
        "keywordstyle" = "{\\footnotesize\\color{blue}}",
        "commentstyle" = "{\\color{Rcomment}\\ttfamily\\itshape}",
        "literate" = "{<-}{{$\\leftarrow$}}2{<<-}{{$\\twoheadleftarrow$}}2",
        "alsoother" = "{$}",
        "alsoletter" = "{.<-}",
        "otherkeywords" = "{!,!=,~,$,*,\\&,\\%/\\%,\\%*\\%,\\%\\%,<-,<<-,/}")
)
SweaveListingPreparations()
## Add the packages you use and want to get highlighted
library(RODBC)
library(RMySQL)
\end{Scode}

or alternative

\RequirePackage{listings}
\RequirePackage{Sweave}

<<label=SweaveListingsPreparations , results=tex , echo=FALSE>>=
require(SweaveListingUtils)
SweaveListingOptions(Rcolor=c(0,0,0), overwrite=TRUE,
    Keywordstyle="{\\footnotesize\\color{blue}}",
    interm.Keywordstyle="{\\footnotesize\\color{blue}}",
    Rset=list("fancyvrb" = "true", "language" = "R", "escapechar" = "`",
        "basicstyle" = "{\\footnotesize\\color{Rcolor}}",
        "keywordstyle" = "{\\footnotesize\\color{blue}}",
        "commentstyle" = "{\\color{Rcomment}\\ttfamily\\itshape}",
        "literate" = "{<-}{{$\\leftarrow$}}2{<<-}{{$\\twoheadleftarrow$}}2",
        "alsoother" = "{$}",
        "alsoletter" = "{.<-}",
        "otherkeywords" = "{!,!=,~,$,*,\\&,\\%/\\%,\\%*\\%,\\%\\%,<-,<<-,/}")
)
SweaveListingPreparations()
## Add the packages you use and want to get highlighted
library(RODBC)
library(RMySQL)
@

The code chunk generate all the definitions needed to setup the highlighting. You may skip the SweaveListingOptions function, it just redefines the highlighting. You now can process your Sweave document as you normal do. One option is to include this in a seperate Sweave document and use \input to include it afterwards. An example is given as a vignette to the SweaveListingUtils package.

Leave a Reply