I am following this example in an attempt to add highlighting to rows of a LaTeX table created by xtable
. In my version, I want to add highlighting to rows conditional upon column c
having a value of 1. Here's my R
code to generate the table.
<<example>>=
# create data frame
my.df=data.frame(a=c(1:10),b=letters[1:10],c=sample(c(0,1), 10, replace=TRUE))
# identify index of rows to highlight
row.i.1 <- which(my.df$c==1)
print(xtable(my.df),
only.contents=TRUE,
include.rownames=FALSE,
include.colnames=FALSE,
hline.after=NULL,
type="latex",
add.to.row=list(
pos=list(as.list(row.i.1))[[1]],
command=rep("\\rowcolor{green!20!white}",
length(seq(from=1,to=length(row.i.1),by=1)))),
sanitize.text.function=identity
)
@
This produces the following table:
% latex table generated in R 3.0.1 by xtable 1.7-1 package
% Mon Nov 11 23:31:51 2013
1 & a & 1.00 \\
\rowcolor{green!20!white} 2 & b & 1.00 \\
\rowcolor{green!20!white} 3 & c & 1.00 \\
\rowcolor{green!20!white} 4 & d & 0.00 \\
5 & e & 1.00 \\
\rowcolor{green!20!white} 6 & f & 0.00 \\
7 & g & 0.00 \\
8 & h & 1.00 \\
\rowcolor{green!20!white} 9 & i & 0.00 \\
10 & j & 1.00 \\
\rowcolor{green!20!white}
As you can see, the \rowcolors are shifted down by 1 row. It should be:
\rowcolor{green!20!white} 1 & a & 1.00 \\
\rowcolor{green!20!white} 2 & b & 1.00 \\
\rowcolor{green!20!white} 3 & c & 1.00 \\
4 & d & 0.00 \\
\rowcolor{green!20!white} 5 & e & 1.00 \\
6 & f & 0.00 \\
7 & g & 0.00 \\
\rowcolor{green!20!white} 8 & h & 1.00 \\
9 & i & 0.00 \\
\rowcolor{green!20!white} 10 & j & 1.00 \\
What is causing this? I have a few extras in my print(xtable())
command to fit my situation, but I don't think they matter for this example.
This works for me. Notice that I substracted one from pos
values.
print(xtable(my.df),
only.contents=TRUE,
include.rownames=FALSE,
include.colnames=FALSE,
hline.after=NULL,
type="latex",
add.to.row=list(
pos=list(as.list(row.i.1-1))[[1]],
command=rep("\\rowcolor{green!20!white}",
length(seq(from=1,to=length(row.i.1),by=1)))),
sanitize.text.function=identity
)