I just would like to point at a combination of Christoph's block entry (here) and Gabor's answer in the R mail list (here) working with the xtable
package. Furthermore, this solution is capable of merging cells in the multirow
manner.
Here comes a MWE:
require(xtable)
# set up data frame
df <- data.frame(c(replicate(2, c("L1")), replicate(2, c("L2"))),
replicate(4, "b"),
replicate(4, runif(4, 1, 10)) )
# only needed if first column consists of numbers
df[[1]] <- as.character(df[[1]])
rle.lengths <- rle(df[[1]])$lengths
first <- !duplicated(df[[1]])
df[[1]][!first] <- ""
# define appearance of multirow
df[[1]][first] <-
paste0("\midrule\multirow{", rle.lengths, "}{*}{\textbf{", df[[1]][first], "}}")
strCaption <- paste0("\textbf{Table Whatever} This table is just produced with some ",
"random data and does not mean anything. Just to show you how ",
"things work.")
# set up xtable output
print(xtable(df, digits = c(0, 0, 0, 3, 1, 0, 6), # first zero "represents" row numbers which we skip later
align = "lllrr|rr", # align and put a vertical line (first "l" again represents column of row numbers)
caption = strCaption, label = "testTable"),
size = "footnotesize", #Change size; useful for bigger tables "normalsize" "footnotesize"
include.rownames = FALSE, #Don't print rownames
include.colnames = FALSE, #We create them ourselves
caption.placement = "top", #"top", NULL
hline.after=NULL, #We don't need hline; we use booktabs
floating=TRUE, # whether egin{Table} should be created (TRUE) or not (FALSE)
sanitize.text.function = force, # Important to treat content of first column as latex function
add.to.row = list(pos = list(-1,
2,
nrow(df)),
command = c(paste("\toprule
", # NEW row
"\multicolumn{2}{c}{} & \multicolumn{2}{c}{\textbf{colLabel1}} & \multicolumn{2}{c}{colLabel2} \\
",
"\cmidrule(l){3-4} \cmidrule(l){5-6}
",
" & & a1 & a2 & a3 & a4 \\
", # NEW row
"\midrule
"
),
paste("\cmidrule(l){3-4} \cmidrule(l){5-6}
" # we may also use 'pos' and 'command' to add a midrule
),
paste("\bottomrule
" # paste is used as it is more flexible regarding adding lines
)
)
)
)
Which knits the following table in LaTeX:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…