【问题标题】:Simple example of using tables + knitr for latex使用表格 + knitr for latex 的简单示例
【发布时间】:2015-08-14 08:22:31
【问题描述】:

我正在为 tables 包苦苦挣扎,可打包文档中的所有示例都非常复杂,它们都不适用于 knitr 和乳胶。有人可以帮忙在标题中显示一个带有一些公式和多行标签的简单表格吗?

类似这样的:

df <- data.frame(matrix(1:9, nrow = 3))
colnames(df) <- c("first column", "second \\frac{1}{2}", "third column first line \\ second line")

提前谢谢你

【问题讨论】:

  • 你对使用“表格”一无所知吗?我推荐 pander 与 pandoc 结合使用。它提供的自定义选项较少,但主要是做“正确的事情”。

标签: r latex knitr tables-package


【解决方案1】:

可以使用xtable 包为 LaTeX 中的表格创建多行标题。这些可以从 .Rmd 或 .Rnw 文件编译。以 mattw 的示例为基础,并在 print 方法中为 xtable 使用 add.to.row

df <- data.frame(matrix(1:50, nrow = 10))

print(
  xtable(df),
  include.rownames = FALSE,
  include.colnames = FALSE,
  add.to.row = list(
    pos = list(0),
    command = c(
      "& \\multicolumn{4}{c}{4 column header} \\\\
       \\cline{2-5}
      col1 & col2 & col3 & col4 & col5 \\\\ "
    )
  )
)

请注意,add.to.row 需要一个包含两个元素的列表:pos 和 command。第一个必须是列表,第二个必须是字符串或向量,请参阅?print.xtablepos 给出了 LaTeX 插入的行号,command 是插入。格式化时要小心,因为如果您不输入空格或\n,它将直接运行到第一列的下一个单元格。

有很多自定义选项,允许您通过一些调整来创建相当复杂的表格。

print(
  xtable(df),
  include.rownames = FALSE,
  include.colnames = FALSE,
  hline.after = c(-1,0),
  add.to.row = list(
    pos = list(0,5,10),
    command = c(
      "& \\multicolumn{4}{c}{4 column header} \\\\
       \\cline{2-5}
      col1 & col2 & col3 & col4 & col5 \\\\ ",
      "\\hline \\multicolumn{5}{l}{Separator in table.} \\\\ \\hline",
      "\\hline \\multicolumn{5}{l}{Notes at end of table.} \\\\ "
    )
  )
)

在此示例中,我更改了 xtable 放置 \hline 的默认设置,允许我在注释上方添加最后一个 \hline - 有助于解释表格中的上标。

还要注意 \cline{2-5} 的使用,在第 2 - 5 列上给我一行。

请参阅gist 了解完全可重现的示例。

【讨论】:

  • 您写了“这在 RMarkdown 中是可以实现的”,但随后提出了 LaTeX 解决方案?我很困惑……
  • 是的,我同意你的观点。我的意思是它可以通过 .Rmd 实现,尽管基础是通过 xtable 使用 LaTeX。我会调整我的答案以反映这一点。
【解决方案2】:

如果您希望表格采用 LaTeX 样式,我认为 RMarkdown 不可能做到这一点。但是,当您在 .Rnw 文件中编写代码时,您可以使用 xtable 包轻松完成此操作:

\documentclass{article}
\begin{document}
<<>>=
library("xtable")
df <- data.frame(matrix(1:9, nrow = 3))
colnames(df) <- c("first column", "second $\\frac{1}{2}$",
                  "third column")
@
<<xtable, results = "asis">>=
print(xtable(df), floating = TRUE,
      sanitize.colnames.function = identity, type = "latex")
@
\end{document}

【讨论】:

  • 感谢您的回答,还有一个问题,是否可以有一个多行标题?我更新了问题?
  • 我还没有这样做。我希望这个链接可以帮助你一点:How to put a newline into a column header in an xtable in R
  • 是的,谢谢,我来过这里。由于某种原因,它不能用 knitr 为我编译
  • 那篇文章非常有帮助,但正如他们所指出的,所使用的对齐技术不适用于表格的最后一列,这使得在每个列内对齐时很难将所有列设为多行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-16
  • 1970-01-01
  • 1970-01-01
  • 2010-11-06
  • 1970-01-01
相关资源
最近更新 更多