我想将data.frame转换为带有多列的(booktab)乳胶表,但是我无法创建将\toprule
放在表格顶部的输出。使用以下数据
dat <- structure(c(841.8, 804.4, 135.1, 106.2, 0.7025, 0.09645, 305.2,
707.1, 449.3, 119.9, 0.7025, 0.09645), .Dim = c(2L, 6L), .Dimnames = list(
c("ev", "smooth"), c("Mean", "SD", "best", "Mean", "SD",
"best")))
> dat
Mean SD best Mean SD best
ev 841.8 135.1 0.70250 305.2 449.3 0.70250
smooth 804.4 106.2 0.09645 707.1 119.9 0.09645
addtorow <- list()
addtorow$pos <- list(-1)
addtorow$command <- '& \\multicolumn{3}{c}{Tab a}& \\multicolumn{3}{c}{Tab b}\\\\'
print(xtable(dat), add.to.row=addtorow, include.colnames=TRUE,booktabs=TRUE)
输出看起来几乎正确,但\toprule
位置错误。
\begin{table}[ht]
\centering
\begin{tabular}{rrrrrrr}
& \multicolumn{3}{c}{In-sample}& \multicolumn{3}{c}{Out-of-sample}\\
\toprule
& Mean & SD & best & Mean & SD & best \\
\midrule
ev & 841.80 & 135.10 & 0.70 & 305.20 & 449.30 & 0.70 \\
smooth & 804.40 & 106.20 & 0.10 & 707.10 & 119.90 & 0.10 \\
\bottomrule
\end{tabular}
\end{table}
更改addtorow$pos<-list(0)
不是一个答案,因为它正确放置了最高规则,但将多列行放在表的列名下面。我正在寻找以下输出:
\begin{table}[ht]
\centering
\begin{tabular}{rrrrrrr}
\toprule
& \multicolumn{3}{c}{In-sample}& \multicolumn{3}{c}{Out-of-sample}\\
& Mean & SD & best & Mean & SD & best \\
\midrule
ev & 841.80 & 135.10 & 0.70 & 305.20 & 449.30 & 0.70 \\
smooth & 804.40 & 106.20 & 0.10 & 707.10 & 119.90 & 0.10 \\
\bottomrule
\end{tabular}
\end{table}
非常感谢任何评论。
答案 0 :(得分:2)
我强烈建议您使用惊人的kableExtra
package。
\documentclass{article}
\usepackage{booktabs}
\begin{document}
<<setup, include=FALSE>>=
library(knitr)
opts_chunk$set(echo=FALSE)
library(kableExtra)
options(knitr.table.format = "latex")
dat <- structure(c(841.8, 804.4, 135.1, 106.2, 0.7025, 0.09645, 305.2,
707.1, 449.3, 119.9, 0.7025, 0.09645), .Dim = c(2L, 6L), .Dimnames = list(
c("ev", "smooth"), c("Mean", "SD", "best", "Mean", "SD",
"best")))
@
<<results='asis'>>=
kable(dat, booktabs = TRUE, caption = "My table", align = "c") %>%
add_header_above(c(" ", "Tab a"=3, "Tab b"=3)) %>%
kable_styling(latex_options = "hold_position")
@
\end{document}