rr-markdownquartokableextra

How to achieve output of `kbl()` while hiding `kbl()` call?


I want the displayed code to omit the kbl() as in the tbl-without-kbl chunk while producing output matches that of tbl-with-kbl. In short, I want the code that is displayed to be optimised for copy-pasting by the user (no kbl()), but for the actual output (in the book) to look good (with kbl(), it looks good in both HTML and PDF).

I have tried putting the kableExtra::kbl() call in the chunk options but the table doesn't look the same.

Is there any way to do this?

---
title: "Stuff with tables"
author: Ian D. Gow
format: pdf
---

```{r}
#| include: false
library(dplyr, warn.conflicts = FALSE)
library(kableExtra)
```

```{r}
dt <- mtcars[1:5, 1:6]
```

```{r}
#| label: tbl-with-kbl
#| tbl-cap: "Table with `kbl()`"
dt |> 
  kbl(booktabs = TRUE)
```

```{r}
#| label: tbl-without-kbl
#| tbl-cap: "Table without `kbl()`"
dt
```

Solution

  • Following the R Markdown Cookbook one option would be to use a custom print method like so:

    ---
    title: "Stuff with tables"
    format: pdf
    ---
    
    ```{r}
    knit_print.data.frame <- function(x, ...) {
      res <- paste(c("", "", kableExtra::kbl(x, booktabs = TRUE)),
        collapse = "\n"
      )
      knitr::asis_output(res)
    }
    
    registerS3method(
      "knit_print", "data.frame", knit_print.data.frame,
      envir = asNamespace("knitr")
    )
    ```
    
    ```{r}
    #| include: false
    library(kableExtra)
    ```
    
    ```{r}
    dt <- mtcars[1:5, 1:6]
    ```
    
    ```{r}
    #| label: tbl-with-kbl
    #| tbl-cap: "Table with `kbl()`"
    dt |>
      kbl(booktabs = TRUE)
    ```
    
    ```{r}
    #| label: tbl-without-kbl
    #| tbl-cap: "Table without `kbl()`"
    dt
    ```
    

    enter image description here