Changing the Color of negative numbers to Red in a table generated with xtable()? Changing the Color of negative numbers to Red in a table generated with xtable()? r r

Changing the Color of negative numbers to Red in a table generated with xtable()?


You can use capture.output() to capture the lines printed by the (implicit) call to print.xtable(). Then apply gsub() to the output, using a pattern and replacement that surround each negative number with \textcolor{red}{}. Finally, use cat() with sep="\n" to write the modified lines out to the *.tex file.

\documentclass{article}\begin{document}<<simpleExamp, results="asis", echo=FALSE>>=library(knitr)library(xtable)testMatrix <- matrix(c(sample(-10:10,10)), ncol = 2)## I added the following three linesxt <- capture.output(xtable(testMatrix))xt_mod <- gsub("(\\s|^)(-\\d*)", "\\1\\\\textcolor{red}{\\2}", xt)cat(xt_mod, sep="\n")@\end{document}

(Note also that I replaced results=tex with results="asis", which knitr 'prefers' and which it will more quickly process.)


Edit: Adding an image of the resulting table. (Getting it in an SO-ready form required a few tweaks to the code, which is also included below.)

enter image description here

\documentclass{standalone}\renewenvironment{table}{}{}% Ignore `table` environment in standalone mode.\begin{document}<<simpleExamp, results="asis", echo=FALSE>>=library(knitr)library(xtable)cat("\\Huge\n\n")testMatrix <- matrix(c(sample(-10:10,10)), ncol = 2)## I added the following three linesxt <- capture.output(print.xtable(xtable(testMatrix), table.placement=NULL))xt_mod <- gsub("(\\s|^)(-\\d*)", "\\1\\\\textcolor{red}{\\2}", xt)cat(xt_mod, sep="\n")@\end{document}


Copied Josh O'Brien's answer with a little tweak to color a table with decimals:

\documentclass{article}\begin{document}<<simpleExamp, results="asis", echo=FALSE>>=library(knitr)library(xtable)testMatrix <- matrix(c(sample(-10:10,10)), ncol = 2)*1.1## I added the following three linesxt <- capture.output(xtable(testMatrix))xt_mod <- gsub("(\\s|^)(-\\d\\.\\d*)", "\\1\\\\textcolor{red}{\\2}", xt)cat(xt_mod, sep="\n")@\end{document}