R,knitr,xtable,交替行颜色 [英] R, knitr, xtable, alternating row colors
问题描述
我试图使用 knitr
在交替行颜色中生成一个带有 xtable
的表。我可以在PDF输出中打印一个表,但不能完全弄清楚 xtable $ c $中的
add.to.row
命令c>手动以及 colortbl
包。
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.
推荐答案
使用底部的代码生成。我希望你不要打破你的眼睛检测浅灰色(我几乎有,在我的一个屏幕上)。
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))
关键是定义行索引( rws
)及其各自的颜色( 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}
这篇关于R,knitr,xtable,交替行颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!