我正在使用knitr和xtable自动执行报告过程。我要突出显示表格的几行,并在每行上方突出显示一条水平线。我正在使用的.Rnw文件如下所示:
\usepackage{colortbl, xcolor}
\usepackage{longtable}
\begin{document}
<<do_table, results = "asis">>=
library(xtable)
mydf <- data.frame(id = 1:10, var1 = rnorm(10), var2 = runif(10))
print(xtable(mydf), add.to.row = list(pos = list(0,2), command = rep("\\rowcolor[gray]{0.75}",2)),hline.after=c(0,2))
@
\end{document}
这可以正常工作,但是,如果我将代码的最后一行调整为
print(xtable(mydf), add.to.row = list(pos = list(0,2), command = rep("\\rowcolor[gray]{0.75}",2)),hline.after=c(0,2),tabular.environment="longtable",floating=FALSE)
输出非常难看,并且行未按预期突出显示。有人知道这个问题的答案吗?
谢谢,
大卫
最佳答案
您处在正确的轨道上,但我有些困惑:您是否要用hline
和rowcolor
突出显示选定的行?根据我的经验,单独使用rowcolor看起来更好,因此我将在下面的答案中假定(但是您可以轻松地同时使用这两个方法,只需附加\\hline
命令)。
另外,下面的所有代码都假定您使用LaTeX booktabs
软件包,该软件包给出正确的加权规则(与hline不同)。老实说,我一直都在使用书签,并且我不费心地将代码调整为使用hline;但是,如果您更喜欢hline,请将所有\toprule
,\midrule
和\bottomrule
宏替换为\hline
。
您似乎已经错过了LaTeX longtables需要一个特殊的标头,并且我们也需要将其作为元素提供给command
列表的add.to.row
向量(这可能是您的排版表看起来不好的原因)。
longtable.xheader <-
paste("\\caption{Set your table caption.}",
"\\label{tab:setyourlabel}\\\\ ",
"\\toprule ",
attr(xtable(mydf), "names")[1],
paste(" &", attr(xtable(mydf), "names")[2:length(attr(xtable(mydf), "names"))], collapse = ""),
"\\\\\\midrule ",
"\\endfirsthead ",
paste0("\\multicolumn{", ncol(xtable(mydf)), "}{c}{{\\tablename\\ \\thetable{} -- continued from previous page}}\\\\ "),
"\\toprule ",
attr(xtable(mydf), "names")[1],
paste("&", attr(xtable(mydf), "names")[2:length(attr(xtable(mydf), "names"))], collapse = ""),
"\\\\\\midrule ",
"\\endhead ",
"\\midrule ",
paste0("\\multicolumn{", as.character(ncol(xtable(mydf))), "}{r}{{Continued on next page}}\\\\ "),
"\\bottomrule \\endfoot ",
"\\bottomrule \\endlastfoot ",
collapse = "")
处理完之后,继续
print
xtable:print(xtable(mydf),
floating = FALSE, % since longtable never floats
hline.after = NULL, % hline off since I use booktabs
add.to.row = list(pos = list(-1,
c(0, 2),
nrow(xtable(mydf))),
command = c(longtable.xheader,
"\\rowcolor[gray]{0.75}\n",
"%")), % comments out a spurious \hline by xtable
include.rownames = FALSE, % depends on your preference
include.colnames = FALSE, % depends on your preference
type = "latex",
tabular.environment = "longtable",
% xtable tries to escape TeX special chars, can be annoying sometimes
sanitize.text.function = function(x){x},
% not all dashes are meant to be math negative sign, set according to your data
math.style.negative = FALSE)
我希望我在答案中使用书夹不要让您感到困惑。
继续编织!