我只想指出 Christoph 的块条目(此处)和 Gabor 在 R 邮件列表(此处)中使用该xtable
包的答案的组合。此外,该解决方案能够以这种方式合并单元格\multirow
。
这是一个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 \begin{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 \n", # NEW row
"\\multicolumn{2}{c}{} & \\multicolumn{2}{c}{\\textbf{colLabel1}} & \\multicolumn{2}{c}{colLabel2} \\\\\n",
"\\cmidrule(l){3-4} \\cmidrule(l){5-6}\n",
" & & a1 & a2 & a3 & a4 \\\\\n", # NEW row
"\\midrule \n"
),
paste("\\cmidrule(l){3-4} \\cmidrule(l){5-6}\n" # we may also use 'pos' and 'command' to add a midrule
),
paste("\\bottomrule \n" # paste is used as it is more flexible regarding adding lines
)
)
)
)
在 LaTeX 中编织下表: