It's probably possible to do this with the tables
package, but xtable
provides a very easy solution. The following minimal example shows two different approaches:
\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}
The first approach (chunk ChangeColumnType
) is very simple: It sets the column type of column 2 to p{4cm}
. That gives a column that is 4cm wide with automatic text wrapping (see wikibooks.org for more details). The drawback is, that this affects the whole column, not only the cell in the first row.
The second approach (chunk ChangeOnlyCell
) uses default alignment (or whatever you want to specify via align
) and changes only the column type of the problematic cell using \multcolumn
.
By default, xtable
"sanitizes" your table, meaning that all special latex characters will be escaped. This is handy because you cannot (easily) break your TEX code, but here we manually want to inject LaTeX code, so we have to turn this off. Therefore, set sanitize.colnames.function = identiy
. All column names will be used as you specify them – so be careful when using characters with a special meaning in LaTeX.
The example from above delivers the following tables:
