Conditionally Formatting Negative Numbers in xtable

Making negative numbers red

In spreadsheets it is usually easy to get red text for negative numbers using conditional formatting. This was the first thing I missed about spreadsheets when I started using LaTeX. For users of the xtable package in R, it is possible to conditionally format negative numbers to red via a little bit of regex work.

The function below takes the output of xtable as input. The output will be ready to paste into a LaTeX document, or to cat into a .Rnw file.

redneg <- function(xt) { gsub("(\\s|^)([-]\\d+\\.?\\d*)","\\1\\\\textcolor{red}{\\2}",xt) }

home