Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R, knitr, xtable, alternating row colors

Tags:

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.

like image 306
Jeremy Yeo Avatar asked May 16 '13 05:05

Jeremy Yeo


1 Answers

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} 
like image 53
Roman Luštrik Avatar answered Sep 21 '22 11:09

Roman Luštrik