我最终使用tables
包knitr
,但我无法弄清楚如何获得多行标题。这是代码:
<<test_table, results='asis', echo=FALSE>>=
matrix <- matrix(1:9, nrow = 3)
colnames(matrix) <- c("first column", "seconf column which I want to have 2 lines because of its very long header title", "third column")
library(tables)
table <- as.tabular(matrix)
latex(table)
@
答案 0 :(得分:0)
使用tables
包可能会这样做,但xtable
提供了一个非常简单的解决方案。以下最小示例显示了两种不同的方法:
\documentclass{article}
\begin{document}
<<setup, echo = FALSE>>=
library(xtable)
library(knitr)
opts_chunk$set(echo = FALSE, results = "asis")
matrix <- matrix(1:9, nrow = 3)
colnames(matrix) <- c(
"first column",
"second column which I want to have 2 lines because of its very long header title",
"third column")
@
<<ChangeColumnType>>=
print(xtable(matrix, align = c("r", "r", "p{4cm}", "r")), include.rownames = FALSE)
@
<<ChangeOnlyCell>>=
colnames(matrix)[2] <- "\\multicolumn{1}{p{4cm}}{second column which I want to have 2 lines because of its very long header title}"
print(xtable(matrix), include.rownames = FALSE, sanitize.colnames.function = identity)
@
\end{document}
第一种方法(块ChangeColumnType
)非常简单:它将第2列的列类型设置为p{4cm}
。这提供了一个4厘米宽的列,带有自动文本换行功能(有关详细信息,请参阅wikibooks.org)。缺点是,这会影响整个列,而不仅仅是第一行中的单元格。
第二种方法(块ChangeOnlyCell
)使用默认对齐(或您想通过align
指定的任何对象)并仅使用\multcolumn
更改有问题单元格的列类型。
默认情况下,xtable
“清理”您的表格,这意味着所有特殊的乳胶字符都将被转义。这很方便,因为你不能(轻松)破坏你的TEX代码,但在这里我们手动想要注入LaTeX代码,所以我们必须关闭它。因此,请设置sanitize.colnames.function = identiy
。所有列名都将在您指定时使用 - 因此在LaTeX中使用具有特殊含义的字符时要小心。