R, knitr, xtable, alternating row colors

落花浮王杯 提交于 2019-11-29 23:32:26
Roman Luštrik

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}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!