I am printing a LaTeX table in R with xtable.
I would like to insert a double line (\\[-1.8ex]\hline
\hline \\[-1.8ex]) instead of the first line (simple \hlineor \topline).
How could I do it automatically?
Example:
table <- data.frame(a=rep(1,2),b=rep(2,2))
print(xtable(table,type = "latex"),
hline.after = c(-1, 0, nrow(table)-1,nrow(table)))
Result
\begin{table}[ht]
\centering
\begin{tabular}{rrr}
\hline
& a & b \\
\hline
1 & 1.00 & 2.00 \\
\hline
2 & 1.00 & 2.00 \\
\hline
\end{tabular}
\end{table}
Desiderata:
\begin{table}[ht]
\centering
\begin{tabular}{rrr}
\\[-1.8ex]\hline
\hline \\[-1.8ex]
& a & b \\
\hline
1 & 1.00 & 2.00 \\
\hline
2 & 1.00 & 2.00 \\
\hline
\end{tabular}
\end{table}
I think your best bet is to use add.to.row, as described in 5.9 here.
In your case it could be something like
library(xtable)
table <- data.frame(a=rep(1,2),b=rep(2,2))
tab <- xtable(table, type="latex")
addtorow <- list(
pos=list(-1),
command=c("\\\\[-1.8ex]\\hline")
)
print(tab, type="latex", add.to.row=addtorow)
producing

Or a bit more elegantly, removing the top line and replacing it with a double one
add <- list(
pos=list(-1),
command=c(
"\\\\[-2ex]\\hline
\\hline \\\\[-2ex]")
)
print(tab, type="latex", add.to.row=add, hline.after=c(0:nrow(table)))
% latex table generated in R 3.5.0 by xtable 1.8-2 package
% Mon Jul 22 18:32:44 2019
\begin{table}[ht]
\centering
\begin{tabular}{rrr}
\\[-2ex]\hline
\hline \\[-2ex] & a & b \\
\hline
1 & 1.00 & 2.00 \\
\hline
2 & 1.00 & 2.00 \\
\hline
\end{tabular}
\end{table}

Just got a cool answer from the author of KableExtra:
How to add double lines to the top and bottom of a table with KableExtra? #546 https://github.com/haozhu233/kableExtra/issues/546 haozhu233 commented 11 hours ago • The most direct solution is to use some simple regex. Note that you'd better put them at the very end because I remember some features of kableExtra rely on the location of toprule to do its tricks.
library(kableExtra)
kbl(mtcars[1:5, 1:5], booktabs = T) %>%
sub("\\\\toprule", "\\\\midrule\\\\midrule", .) %>%
sub("\\\\bottomrule", "\\\\midrule\\\\midrule", .)
This solves the problem to add double lines to the top and bottom at the same time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With