繁体   English   中英

如何使用 flextable 或 gtsummary 中的列跨越 header

[英]How to span header with column in flextable or gtsummary

我怎样才能得到这个

library(dplyr)
library(flextable)  
  mtcars %>% 
    select(mpg, cyl, am) %>% 
    group_by(cyl, am) %>% 
    summarise(mean_mpg = mean(mpg),
              sd_mpg = sd(mpg)) %>% 
    flextable()

在此处输入图像描述

对此:

在此处输入图像描述

您还可以使用tabulator() + as_flextable()函数:

library(dplyr)
library(flextable)  
mtcars %>% 
  select(mpg, cyl, am) %>% 
  group_by(cyl, am) %>% 
  summarise(mean_mpg = mean(mpg),
            sd_mpg = sd(mpg)) %>% 
  tabulator(rows = "cyl", columns = "am",
            `μ` = as_paragraph(mean_mpg), 
            `σ` = as_paragraph(sd_mpg)) |> 
  as_flextable()

在此处输入图像描述

我们需要tidyr::pivot_wider()ftExtra::span_header() 如果您希望在列之间留出空白,请使用 flextable 中的“空” flextable

library(tidyr)
library(dplyr)
library(flextable)  

mtcars %>% 
  select(mpg, cyl, am) %>% 
  group_by(cyl, am) %>% 
  summarise(mean_mpg = mean(mpg),
            sd_mpg = sd(mpg)) %>% 
  pivot_wider(names_from = am, values_from = c(mean_mpg, sd_mpg), names_glue = "am {am}.{.value}", names_vary = "slowest") %>% 
  flextable(col_keys = c(names(.)[1],"blank1",names(.)[2:3], "blank2", names(.)[4:5] )) |> 
  ftExtra::span_header(sep = "\\.") |> 
  empty_blanks()

在此处输入图像描述

①如果本文未解决您的问题,请点击查看与本文相关的问题
②如果本文未解决您的问题,请向程序员专用AI小助手提问
暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM