(This article was first published on The Praise of Insects, and kindly contributed to R-bloggers)
Recently, while typing up an R tutorial, I used the LaTeX fancyvrb package to create two environments—one coloured blue for R commands, and one coloured red to display R output. This worked well for large blocks of each type. Then I decided I wanted to display a number of one-line commands and output alternately. Looking up the fancyvrb package documentation, it was easy to get alternate colours. The problem was, it did it globally. My environments for input and output also went psychedelic.After a bit of messing around, I discovered the following solution. My red environments remain red, my blue environments stay blue, and alternate colours only turn up when I want them to!
\documentclass{article}
\usepackage{fancyvrb}
\usepackage{color}
\newcommand{\ChangeLine}[1]{%
\ifodd\value{FancyVerbLine}%
\textcolor{blue}{#1}\else\textcolor{red}{#1}\fi}
\DefineVerbatimEnvironment{blueEnv}{Verbatim}{formatcom=\color{blue}}{}
\DefineVerbatimEnvironment{redEnv}{Verbatim}{formatcom=\color{red}}{}
\DefineVerbatimEnvironment{alternate}{Verbatim}{formatcom=\renewcommand{\FancyVerbFormatLine}{\ChangeLine}}{}
\begin{document}
\begin{Verbatim}
aaaaaaaaaaa
bbbbbbbbbb
cccccccccccc
ddddddddddddd
\end{Verbatim}
\begin{blueEnv}
aaaaaaaaaaa
bbbbbbbbbb
cccccccccccc
ddddddddddddd
\end{blueEnv}
\begin{redEnv}
aaaaaaaaaaa
bbbbbbbbbb
cccccccccccc
ddddddddddddd
\end{redEnv}
\begin{alternate}
aaaaaaaaaaa
bbbbbbbbbb
cccccccccccc
ddddddddddddd
\end{alternate}
\end{document}
To leave a comment for the author, please follow the link and comment on his blog: The Praise of Insects.
R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

Zero Inflated Models and Generalized Linear Mixed Models with R.
Zuur, Saveliev, Ieno (2012).