问题
I want to convert a data.frame into a (booktab) latex table with multicolumns but I fail to create output which puts the \toprule
on top of the table. The following data is used
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)
The output looks almost correct, but the \toprule
is on the wrong position.
\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}
Changing addtorow$pos<-list(0)
is not an answer as it places the top rule correctly but puts the multicolumn row below the column-names of the table. I am looking for the following output:
\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}
Any comment is greatly appreciated.
回答1:
I strongly recommend to use the amazing 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}
来源:https://stackoverflow.com/questions/44324042/r-xtable-with-multicolumns-and-booktabs