I'm trying to produce a table with xtable
in R using knitr
with alternating row colors. I can print a table in the PDF output but can't quite figure out the add.to.row
command in the xtable
manual along with the colortbl
package.
Asked
Active
Viewed 9,482 times
24

Jeremy Yeo
- 493
- 4
- 9
-
5It's often helpful to provide a minimum working example of what you're trying to do, along with your efforts and where you fail. – Roman Luštrik May 16 '13 at 06:09
-
If you do not insist on coloring but highlighting with (strong) emphasis would fit your needs, then you might give a try to `emphasize.*` functions even with HTML/docx/odt formats in `pander` package: http://blog.rapporter.net/2013/04/hihglight-cells-in-markdown-tables.html – daroczig May 16 '13 at 08:16
-
The package gridExtra [http://stackoverflow.com/questions/18414001/gridextra-colour-different-rows-with-tablegrob][1] offers also nice table formatting. [1]: http://stackoverflow.com/questions/18414001/gridextra-colour-different-rows-with-tablegrob – user2030503 Sep 04 '13 at 15:24
1 Answers
37
This figure was produced using the code at the bottom. I hope you don't break your eyes detecting the light grey color (I almost have, on one of my screens).
library(xtable)
mydf <- data.frame(id = 1:10, var1 = rnorm(10), var2 = runif(10))
rws <- seq(1, (nrow(mydf)-1), by = 2)
col <- rep("\\rowcolor[gray]{0.95}", length(rws))
print(xtable(mydf), booktabs = TRUE,
add.to.row = list(pos = as.list(rws), command = col))
The key is to define row indices (rws
) and their respective colors (col
). If you want colors to differ between rows, you'll need to play around with paste
.
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usepackage{booktabs}
\usepackage{colortbl, xcolor}
\begin{document}
<<do_table, results = "asis">>=
library(xtable)
mydf <- data.frame(id = 1:10, var1 = rnorm(10), var2 = runif(10))
rws <- seq(1, (nrow(mydf)), by = 2)
col <- rep("\\rowcolor[gray]{0.95}", length(rws))
print(xtable(mydf), booktabs = TRUE,
add.to.row = list(pos = as.list(rws), command = col))
@
\end{document}

Steph Locke
- 5,951
- 4
- 39
- 77

Roman Luštrik
- 69,533
- 24
- 154
- 197
-
1you interpretation of _gray code_ highlighting: shades that differ by one hex digit? – baptiste May 16 '13 at 10:43
-
1@baptiste I'm afraid I don't understand the question. My choice of color has no particular motivation. I just picked something more or less at random as it's only for illustrative purposes. – Roman Luštrik May 16 '13 at 10:46
-
Hi Roman, thanks for the code! I know it is some years ago, but do you know how to make the colors start with the first row? Just starting the sequence by 0 gives me a black square. – panuffel Mar 17 '16 at 09:57
-
1@panuffel copy my code, open a new question, show what you've tried and see solutions rain down on you. :) – Roman Luštrik Mar 17 '16 at 10:45