使用knitr和乳胶的多行表标题 [英] multiline table header using knitr and latex

查看:81
本文介绍了使用knitr和乳胶的多行表标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最终将tables包与knitr一起使用,但是我不知道如何获取多行标题.这是代码:

I ended up using tables package with knitr, but I can not figure out how to get a multiline header. Here is the code:

<<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)
@

推荐答案

使用tables包可能可以做到这一点,但是xtable提供了一个非常简单的解决方案.以下最小示例显示了两种不同的方法:

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}

第一种方法(块ChangeColumnType)非常简单:它将列2的列类型设置为p{4cm}.这样一来,该列的宽度为4厘米,并具有自动文本换行功能(请参见 wikibooks.org 了解更多信息).缺点是,这会影响整个列,不仅影响第一行中的单元格.

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.

第二种方法(块ChangeOnlyCell)使用默认对齐方式(或您要通过align指定的任何内容),并使用\multcolumn仅更改有问题的单元格的列类型. 默认情况下,xtable清理"您的表,这意味着所有特殊的乳胶字符都将被转义.这很方便,因为您不能(轻松)破坏TEX代码,但是在这里我们要手动注入LaTeX代码,因此我们必须将其关闭.因此,设置sanitize.colnames.function = identiy.所有列名都将按您指定的方式使用-因此在LaTeX中使用具有特殊含义的字符时要小心.

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:

这篇关于使用knitr和乳胶的多行表标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆