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?

  • $\begingroup$ 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. $\endgroup$
    – mpiktas
    Mar 7 '11 at 11:36
  • $\begingroup$ I need the background of one row to be of a specific color. Do I have to rewrite an xtable function? $\endgroup$ Mar 7 '11 at 11:42
  • 1
    $\begingroup$ 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. $\endgroup$ Mar 7 '11 at 23:27
  • $\begingroup$ @Conjugate You're right, although it is not as straightforward as I would have thought; I've updated my response with your suggestion. $\endgroup$
    – chl
    Mar 8 '11 at 10:26
  • $\begingroup$ @chl 'not straightforward' is an understatement. That function is a beast, although a very capable one. $\endgroup$ 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

m <- matrix(sample(1:10,10), nr=2)
print(xtable(m), add.to.row=list(list(1),"\\rowcolor[gray]{.8} "))

gives me

enter image description here

(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.)


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:

## 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')

Not the answer you're looking for? Browse other questions tagged or ask your own question.