sweave, xtable, longtable and alternating row colors…problems with `add.to.row`

元气小坏坏 提交于 2019-12-06 03:23:11

The trick is to flatten out the list. There may be a prettier way, the following does the trick.

pos=list(as.list(c(0,seq(from=1,to=nrow(my.df),by=2))))[[1]]

The whole package is then:

library(xtable)
my.df=data.frame(a=c(1:10),b=letters[1:10])

print(xtable(my.df,caption="My Table"),
      tabular.environment="longtable",
      floating=FALSE,
      hline.after=c(-1,nrow(my.df)),
      add.to.row=list(
      pos=list(as.list(c(0,seq(from=1,to=nrow(my.df),by=2))))[[1]],
      command=c("\\hline \\endhead ",
      rep("\\rowcolor[gray]{0.8}",length(seq(from=1,to=nrow(my.df),by=2)))))
      )

which produces

% latex table generated in R 2.14.2 by xtable 1.7-0 package
% Thu Jan 31 12:52:55 2013
\begin{longtable}{rrl}
  \hline
 & a & b \\ 
  \hline \endhead 1 &   1 & a \\ 
   \rowcolor[gray]{0.8}2 &   2 & b \\ 
  3 &   3 & c \\ 
   \rowcolor[gray]{0.8}4 &   4 & d \\ 
  5 &   5 & e \\ 
   \rowcolor[gray]{0.8}6 &   6 & f \\ 
  7 &   7 & g \\ 
   \rowcolor[gray]{0.8}8 &   8 & h \\ 
  9 &   9 & i \\ 
   \rowcolor[gray]{0.8}10 &  10 & j \\ 
   \hline
\hline
\caption{My Table}
\end{longtable}

the formatting of the latex is a little ugly, and since \rowcolor is supposed to come before the row, even though we specified 1,3,5,9 we get coloring on 2,4,6,8 of the output.

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