如何在隐藏`kbl()`调用的同时实现`kbl()`的输出?

问题描述 投票:0回答:1

我希望显示的代码省略

kbl()
,如
tbl-without-kbl
块中那样,同时生成与
tbl-with-kbl
匹配的输出。简而言之,我希望显示的代码能够针对用户复制粘贴进行优化(没有
kbl()
),但实际输出(在书中)看起来不错(使用
kbl()
,它在HTML 和 PDF)。

我尝试将

kableExtra::kbl()
调用放入块选项中,但表格看起来不一样。

有什么办法可以做到这一点吗?

---
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
```
r r-markdown quarto kableextra
1个回答
0
投票

遵循 R Markdown Cookbook 一种选择是使用自定义打印方法,如下所示:

---
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
```

© www.soinside.com 2019 - 2024. All rights reserved.