You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用gtsummary生成表格后无法保存为Word文档的问题求助

问题原因

报错Error: Error in argument 'x='. Expecting object of class 'gtsummary'是因为你调用as_gt()后,demographic_table已经变成了gt类对象,而as_flex_table()是gtsummary包的函数,仅接受gtsummary类对象作为输入,因此触发类型不匹配错误。

两种解决方案

方案1:基于flextable直接生成并保存(推荐)

调整代码流程,在转换为gt对象前先转成flextable,并用flextable的方法设置字体:

demographic_table <- df %>% 
  dplyr::select(Group, Diagnose,Gender,Age,Handedness,Cpz_equivalent)%>%
  mutate(
    Gender = case_when(Gender == "female" ~ "Female",
                       Gender == "male" ~ "Male",))%>%
  mutate(
    Group = case_when(Group == "control" ~ "Control",
                      Group == "patient" ~ "Patient",))%>%
  mutate(
    Handedness=case_when(Handedness=='right'~'Right',
                         Handedness=='left'~'Left',))%>%
  tbl_summary(
    by = Diagnose,
    statistic = list(all_continuous() ~ "{mean} ({sd})",
                     all_categorical() ~ "{n} ({p}%)",
                     all_dichotomous()~"{n}"),
    digits = all_continuous() ~ 2,
    type = all_dichotomous()~"categorical",
    label = Cpz_equivalent ~ "Clozapine dose",
    missing = 'no'
  )%>%
  add_p()%>%
  modify_spanning_header(c("stat_1", "stat_2", 'stat_3') ~ "**Diagnose**") %>%
  add_overall()%>%
  bold_labels()%>%
  as_flex_table() %>%  # 转换为flextable对象
  flextable::font(fontname = "Times New Roman", part = "all")  # 设置全局字体

保存代码:

demographic_table %>% flextable::save_as_docx(path = "你的表格文件名.docx")

方案2:基于gt对象直接保存

如果需要保留gt对象的设置,直接用gt包的gtsave()函数保存为Word,无需转flextable:

保存代码修改为:

gt::gtsave(demographic_table, filename = "你的表格文件名.docx")

内容的提问来源于stack exchange,提问作者lotus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:27:26