1
votes

I'm trying to get R to suppress lengthy tables created with kable & kableExtra in the inline Rmd output while keeping them in the final knitted PDF. I only want to do this with a few chunks, so I'd rather not go the route of setting the global option of turning off all of the inline output.

I've gone through several iterations of the chunk options listed here: https://yihui.name/knitr/demo/output/ and here: https://yihui.name/knitr/options/#plots but haven't landed on the right one, so I'm not sure if I'm even looking in the right place or if I've just skipped over the correct setting.

YAML:

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

Code:

```{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")
```

Inline output that I don't want to have pop up every time I run this thing:

\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}

If you can imagine having to scroll through 50-100 lines of this stuff while trying to write code, you can see how annoying and time consuming it gets to be.

1

1 Answers

1
votes

This function detects that an RMarkdown document is being processed inline in RStudio, rather than through knitting:

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

So you could wrap your problematic code in something like

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

or make another function

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

and add it to your pipe:

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

Both of these have the disadvantage of requiring a modification to your code that will be shown if echo=TRUE. I don't think there is any chunk option that is equivalent to hide_inline, but I could be wrong.

If you were really desperate, you could use echo=2:3 or similar to hide the if (!is_inline()) { and } lines.