R - 带有 Flextable 库的 Crosstable 亮点

R - Crosstable highlights with Flextable library

我需要根据下面的示例在交叉表中按行突出显示(使用粗体或某种颜色)最大计数。但我似乎无法在任何地方找到如何在交叉表中做到这一点。有人有提示吗?提前致谢!

library(tidyverse)
library(gtsummary)
library(flextable)

tib <- tibble(x=c(1,2,3,2,2,1,3,2,4,1,2,3,2,2,1,3,2,4),
              y=c("a","b","c","a","b","b","b","b",NA,"a","b","c","a","b","b","b","c",NA))


tib %>%  
  tbl_cross(percent = "row",
            missing_text = "NA") %>% 
  as_flex_table() 

David Gohel 是正确的...这是可能的,但这不是一个简单的解决方案。计数的未格式化(即数字)版本在内部保存在 gtsummary 对象中。我们可以访问它们,找到最大计数,并构造调用以使用 modify_table_styling() 函数将单元格加粗。

示例如下。

library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.5.2'

tib <- tibble::tibble(
  x=c(1,2,3,2,2,1,3,2,4,1,2,3,2,2,1,3,2,4),
  y=c("a","b","c","a","b","b","b","b",NA,"a","b","c","a","b","b","b","c",NA))


tbl <- 
  tib %>%  
  tbl_cross(percent = "row",
            missing_text = "NA")

# find cell(s) with max count per row
df_max_count <- 
  purrr::pluck(tbl, "meta_data", "df_stats", 1) %>% 
  dplyr::filter(!is.na(by)) %>% 
  dplyr::group_by(variable_levels) %>%
  dplyr::filter(n == max(n)) %>%
  dplyr::select(variable_levels, col_name, n) %>%
  dplyr::ungroup()

# construct calls to bold cells
call_list <-
  purrr::map2(
    df_max_count$variable_levels,
    df_max_count$col_name,
    ~rlang::expr(
      modify_table_styling(columns = !!.y,
                           rows = label %in% !!.x,
                           text_format = "bold")
    )
  )

# evaluate calls in tbl_cross
tbl_final <-
  call_list %>%
  purrr::reduce(~ rlang::expr(!!.x %>% !!.y) %>% eval(), .init = tbl)

reprex package (v2.0.1)

创建于 2022-01-31