目前,没有简单的方法可以做到这一点。但是我包含了一个我认为可以解决您的问题的代码示例。
对于 {flextable},调用函数的顺序很重要。运行as_flextable()
然后附加额外的调用似乎并没有得到你想要的。
另一种方法是保存调用,在需要的地方插入新的 flextable 函数调用,然后评估调用。这就是在下面的示例中所做的。
---
title: "Untitled"
output: word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE)
```
```{r}
library(tidyverse)
library(gtsummary)
library(flextable)
set_gtsummary_theme(theme_gtsummary_jama())
tbl <-
mtcars[1:20, c(1, 2, 9, 4)] %>%
tbl_summary(
missing = "ifany",
by = am,
type = list(cyl ~ "categorical")
) %>%
bold_labels() %>%
add_p() %>%
add_overall()
```
### Default Flextable
```{r}
gtsummary::as_flextable(tbl)
```
### Compact Flextable
```{r}
# this function inserts additional flextable calls, then evaluates the calls
update_flextable_calls <- function(x, call_list, after) {
# saving calls that create the flextable
x_calls <- gtsummary::as_flextable(x, return_calls = TRUE)
# adding new calls at `after=`
after_n <- names(x_calls) %in% after %>% which()
x_calls <- c(
x_calls[1:after_n],
call_list,
x_calls[(after_n + 1):length(x_calls)]
)
# evaluating calls
x_calls %>%
unlist() %>%
purrr::compact() %>%
# concatenating expressions with %>% between each of them
purrr::reduce(function(x, y) rlang::expr(!!x %>% !!y)) %>%
# evaluating expressions
eval()
}
# list of calls that make a table compact
compact_calls <- list(
rlang::expr(font(fontname = "Bodoni 72", part = "all")),
rlang::expr(fontsize(size = 8, part = "all")),
rlang::expr(padding(padding.top = 0, part = "all")),
rlang::expr(padding(padding.bottom = 0, part = "all"))
)
# adding the compact calls, and evaluating them
update_flextable_calls(
x = tbl, # gtsummary table
call_list = compact_calls, # calls that make flextable compact
after = "footnote" # add calls after the "footnote" functions
)
```
这显然不是一个很好的永久解决方案。我们有一个名为的主题theme_gtsummary_compact()
,它使 {gt} 表格更紧凑,字体更小,填充更少。我们可以更新主题以使 flextables 更紧凑!如果您在 GitHub 上创建一个问题来更新theme_gtsummary_compact()
flexables,我会很高兴,我们可以合作开发一个适合您的解决方案。
https://github.com/ddsjoberg/gtsummary/issues/new/choose