在循环中的 xtable 数字之间添加部分 headers

Adding section headers in between xtable figures in a loop

我正在使用 knitr 生成 PDF writeup。我想打印一系列 tables,中间有 headers 部分。我在 R 代码块中执行此操作。不幸的是,第一个 header 打印出来,然后是一个数字,然后 header 的其余部分适合该页面,而 table 的其余部分则排在后面而不是根据需要穿插在 header 之间。

在本页之后还有 5 个系列 table 在它们自己的页面上。

这是我正在使用的代码:

dfList <- list(alc_top, alc_bottom, cpg_home_top, cpg_home_bottom, electronics_top, electronics_bottom)
labels <- c("Premium Liquor Brand - Top Performers", "Premium Liquor Brand- Bottom Performers", "CPG Home - Top Performers", "CPG Home - Bottom Performers", "Electronics - Top Performers", "CPG Home - Bottom Performers")

for (i in 1:length(dfList)) {
  df <- dfList[[i]]
  product = "test"
  cat(paste("\section{",labels[i],"}", sep=""))  
  print(xtable(df,size="\tiny"))
}

我尝试在循环中添加新行 cat("\newpage")。这为每个标签添加了一个新页面,但所有图表都再次出现在新部分之后。

我想我需要为 table 指定一个定位值(H 或 h 或 LaTex 中类似的东西),但我不太确定如何使用 xtable和编织者。

这里的问题不是元素写入 TEX 文件的顺序。 PDF 中的“错误顺序”是由于 table 被包裹在浮动环境中,因此它们的 TEX 代码在源文件中的位置不一定对应于 table' s 在 PDF 中的位置。

这里有三个选项可以使 table 保持在固定位置。各有利弊:

选项 1:不使用浮点数

print.xtable 有一个 floating 参数(默认为 TRUE)。将此参数设置为 FALSE 会导致 table 未包装在浮动环境中(默认值:table)。

  • 亲:简单有效。
  • 缺点:Non-floats 没有编号,没有标题也没有标签。如果 floating = FALSE.
  • print.xtable 忽略 xtable 上的 captionlabel 参数

选项 2:位置“H”

print.xtable 有一个 table.placement 参数,可用于将自定义浮动放置说明符传递给浮动环境。说明符 H“将浮点数精确地放置在 LaTeX 代码中的位置”(来源:Wikibooks)。请注意,这需要 \usepackage{float}.

  • 专业版:保留标题、编号和标签。
  • 缺点:需要一个额外的包(几乎不相关)。

选项 3:\FloatBarrier

LaTeX 包 placeins 提供了一个 \FloatBarrier 命令,它强制打印到目前为止未显示的所有浮点数。

  • 优缺点:作为选项 2。
  • 此外,由于需要在每个 table 之后插入 \FloatBarrier 命令,所以代码有点混乱——除非(至少在这个问题的特定情况下)以下内容使用的功能:

The package even provides an option to change the definition of \section to automatically include a \FloatBarrier. This can be set by loading the package with the option [section] (\usepackage[section]{placeins}). [source: Wikibooks]

演示

\documentclass{article}
\usepackage{float}
\usepackage{placeins}
\begin{document}

<<results = "asis", echo = FALSE>>=
library(xtable)

# This table floats.
print(
  xtable(head(cars),
         caption = "Floating",
         label = "tab:floating"), table.placement = "b"
  )

# This table won't float but caption and label are ignored.
print(
  xtable(head(cars),
         caption = "Not floating",
         label = "tab:not-floating"),
  floating = FALSE)

# Placement "H". (requires "float" package)
print(
  xtable(head(cars),
         caption = "Non-floating float",
         label = "tab:not-actually-floating"),
  table.placement = "H")

cat("Text before the barrier. (text 1)")
# Floats won't float beyond this barrier (requires "placeins" package)
cat("\FloatBarrier\n")
cat("Text after the barrier. (text 2)")
@

Add \texttt{table.placement = "b"} to the first table to see that it will be located at the bottom of page 1 (after `text 1') and `text 2` will come \emph{after} it (on page 2), althogh there would be plenty of space on page 1. This is because the float cannot `pass' the barrier.

\end{document}