# How to create coloured tables with Sweave and xtable?

I am using Sweave and xtable to generate a report.

I would like to add some coloring on a table. But I have not managed to find any way to generate colored tables with xtable.

Is there any other option?

-
what is the coloured table? Cells with colour background? Cell text different colour? In the last scenario, the solution might be wrapping the values with appropriate tex commands. –  mpiktas Mar 7 '11 at 11:36
I need the background of one row to be of a specific color. Do I have to rewrite an xtable function? –  RockScience Mar 7 '11 at 11:42
xtable has already been rewritten (or perhaps pre-written) as the latex function in the R package Hmisc. Personally I swear by it for proper looking tables. I haven't checked whether it has room for the fancy insertion trick described below, though I'd be surprised if not. –  conjugateprior Mar 7 '11 at 23:27
@Conjugate You're right, although it is not as straightforward as I would have thought; I've updated my response with your suggestion. –  chl Mar 8 '11 at 10:26
@chl 'not straightforward' is an understatement. That function is a beast, although a very capable one. –  conjugateprior Mar 8 '11 at 12:44

Although I didn't try this explicitly from with R (I usually post-process the Tables in Latex directly with \rowcolor, \rowcolors, or the colortbl package), I think it would be easy to do this by playing with the add.to.row arguments in print.xtable(). It basically expect two components (passed as list): (1) row number, and (2) $\LaTeX$ command. Please note that command are added at the end of the specified row(s).

It seems to work, with the colortbl package. So, something like this

<<result=tex>>
library(xtable)
m <- matrix(sample(1:10,10), nr=2)
@


gives me

(This is a customized Beamer template, but this should work with a standard document. With Beamer, you'll probably want to add the table option when loading the package.)

Update:

Following @Conjugate's suggestion, you can also rely on Hmisc facilities for handling $\TeX$ output, see the many options of the latex() function. Here is an example of use:

library(Hmisc)
## print the second row in bold (including row label)
form.mat <- matrix(c(rep("", 5), rep("bfseries", 5)), nr=2, byrow=TRUE)
w1 <- latex(m, rownamesTexCmd=c("","bfseries"), cellTexCmds=form.mat,
numeric.dollar=FALSE, file='/tmp/out1.tex')
w1  # call latex on /tmp/out1.tex
## highlight the second row in gray (as above)
w2 <- latex(m, rownamesTexCmd=c("","rowcolor[gray]{.8}"),
numeric.dollar=FALSE, file='/tmp/out2.tex')
w2

-
+1, just as I suspected :) –  mpiktas Mar 7 '11 at 12:41
thanks for your answer and the edit. –  RockScience Mar 8 '11 at 15:54