在循环中的xtable数字之间添加节标题

时间:2016-01-25 22:39:01

标签: r latex knitr xtable

我正在使用knitr生成PDF文档。我想打印一系列表格,其中包含节标题。我在R代码块中这样做。不幸的是,会发生的事情是第一个标题打印,然后是一个数字,然后其余的标题适合该页面而其余的表格都在后面而不是根据需要散布在标题中。

screenshot of the pdf output

在此页面之后,在他们自己的页面上还有一系列的表格。

这是我正在使用的代码:

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")。这会为每个标签添加一个新页面,但所有图表都会再次出现在新部分之后。

我认为我需要为表格指定一个定位值(H或h或LaTex中的类似值),但我不确定如何使用xtable和knitr。

1 个答案:

答案 0 :(得分:2)

这里的问题不是元素写入TEX文件的顺序。 &#34;错误的订单&#34; PDF中的表是由于表被包装在浮动环境中,因此它们的TEX代码在源文件中的位置不一定与表中PDF的位置相对应。

以下是将表保持在固定位置的三个选项。每个人都有其优点和缺点:

选项1:不要使用花车

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

  • Pro:简单有效。
  • Con:非浮动没有编号,没有标题,也没有标签。如果print.xtable,则caption会忽略label上的xtablefloating = FALSE个参数。

选项2:职位&#34; H&#34;

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

  • Pro:保留标题,编号和标签。
  • Con:需要一个额外的包(几乎不相关)。

选项3:\ FloatBarrier

LaTeX包placeins提供\FloatBarrier命令,强制打印到此时未显示的所有浮动。

  • 利弊:作为选项2.
  • 此外,由于需要在每个表之后插入\FloatBarrier命令,它会使代码变得混乱 - 除非(至少在此问题的特定情况下)使用以下功能:
  

该软件包甚至提供了一个选项,可以将\section的定义更改为自动包含\FloatBarrier。这可以通过使用选项[section]加载包来设置\usepackage[section]{placeins})。[来源: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}
相关问题