2
我试图用xtable和knitr插入汇总行来制作表格。我想要以不同的颜色插入这些插入的行。使用add.to.row选项,我设法插入行或改变颜色,但不能同时改变颜色。xtable - 添加行的背景颜色
我在xtable中插入行而不是提前的原因是我希望“total”行分布在两列,因为它的长度在我的原始数据集中。因此,所需的解决方案将包含汇总行中的多列单元格和不同颜色的背景。 我在我的Latex学习曲线的一开始,任何帮助将不胜感激。
下面是一个例子,其中包括假数据集:
\usepackage{booktabs}
\usepackage{colortbl, xcolor}
\begin{document}
<<try, echo = FALSE, eval = TRUE, results = 'asis'>>=
library(xtable)
dat <- data.frame(type = c(rep("a", 5), rep("b", 5)), a = c(1:5, 1:5), b = 1:10, c = 21:30)
temp <- ddply(dat, .(type), summarize, SumB = sum(b))
rws <- which(dat$a == 5)
col <- rep("\\rowcolor[gray]{0.95}", length(rws)) ## colour definition prepared, but not used
#Making the command for inserting summary rows
temp$insert <- ""
for(i in 1:nrow(temp)){
temp[i,]$insert <- sprintf("\\multicolumn{3}{l}{Total %s} &
\\multicolumn{1}{c}{%d} \\\\ ", temp[i,]$type, temp[i,]$SumB)
}
print(xtable(dat, align = "llccc"),
include.rownames=FALSE,
booktabs = TRUE,
sanitize.text.function=function(x){x},
add.to.row = list(pos = as.list(rws),
command = paste(temp$insert, sep = ",")))
@
\end{document}
我可能在这里丢失了一些东西,因为我在发布的假数据集上运行它所得到的是带有所有表值的运行行的pdf:“type abc 1 a 1 1 21 2 a 2 2 22 3 a 3 3 23 4 a 4 4 24 5 a 5 5 25 6 b 1 6 26 7 b 2 7 27 8 b 3 8 28 9 b 4 9 29 10 b 5 10 30“...任何提示? – user2602640
在我的示例中,'somextable'对象已经是类'xtable'。这导致了'print.xtable'方法。听起来像你忘了xtable()? –
啊,是的。纠正了这个令人眩目的问题并摆弄了一下之后,它就起作用了。谢谢! – user2602640