在 Rmd 内联输出中抑制冗长的 kable 表,同时保留在最终 PDF 中

Suppressing lengthy kable tables in Rmd inline output while retaining in final PDF

我试图让 R 抑制在内联 Rmd 输出中使用 kable 和 kableExtra 创建的冗长表格,同时将它们保留在最终编织的 PDF 中。我只想用几个块来做这件事,所以我不想走设置关闭所有内联输出的全局选项的路线。

我已经对此处列出的块选项进行了多次迭代:https://yihui.name/knitr/demo/output/ and here: https://yihui.name/knitr/options/#plots 但还没有找到正确的选项,所以我不确定我是否在正确的地方寻找或者如果我刚刚跳过了正确的设置。

YAML:

---
output:
  pdf_document:
    latex_engine: xelatex
---

代码:

```{r}
# Setup
library(knitr)
library(kableExtra)

# Create some data
dat <- data.frame ("A" = c(1:5),
                   "B" = c("Imagine a really long table",
                           "With at least 50 rows or so",
                           "Which get in the way in the inline output",
                           "But I want in the final PDF",
                           "Without influencing the other chunks")
                   )
# Produce the table
kable(dat, booktabs=TRUE, format="latex", longtable=TRUE) %>%
  kable_styling(latex_options="HOLD_position")
```

我不想每次 运行 这个东西时都弹出的内联输出:

\begin{table}[H]
\centering
\begin{tabular}{rl}
\toprule
A & B\
\midrule
1 & Imagine a really long table\
2 & With at least 50 rows or so\
3 & Which get in the way in the inline output\
4 & But I want in the final PDF\
5 & Without influencing the other chunks\
\bottomrule
\end{tabular}
\end{table}

如果您能想象在尝试编写代码时必须滚动浏览 50-100 行这些东西,您就会明白它变得多么烦人和耗时。

此函数检测到 RMarkdown 文档正在 RStudio 中内联处理,而不是通过编织:

is_inline <- function() {
  is.null(knitr::opts_knit$get('rmarkdown.pandoc.to'))  
}

所以您可以将有问题的代码包装成类似

的东西
if (!is_inline()) {
  kable(dat, booktabs=TRUE, format="latex", longtable=TRUE) %>%
  kable_styling(latex_options="HOLD_position")
}

或者创建另一个函数

hide_inline <- function(x) {
  if (is_inline())
    cat("[output hidden]")
  else
    x
}

并将其添加到您的管道中:

kable(dat, booktabs=TRUE, format="latex", longtable=TRUE) %>%
  kable_styling(latex_options="HOLD_position") %>%
  hide_inline()

这两者的缺点是需要修改您的代码,如果 echo=TRUE 将显示该代码。我不认为有任何块选项等同于 hide_inline,但我可能是错的。

如果你真的很绝望,你可以使用 echo=2:3 或类似的方法来隐藏 if (!is_inline()) {} 行。