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

使用gtsummary结合glue包时,通过modify_caption在表格标题中显示分组变量名的问题排查

解决方案:提取裸变量名用于glue标题

我来帮你解决这个问题!你遇到的核心问题是:enquo/{{}}语法能处理tbl_summary的分组参数,但没法直接把裸变量转换成字符串用于glue标题。我们需要用rlang包的工具把捕获的裸变量提取成字符串,就能完美解决这个问题了。

方法1:enquo + as_name 组合

先把裸变量捕获为quosure对象,再转换成字符串用于标题:

library(tidyverse)
library(glue)
library(gapminder)
library(gtsummary)
library(rlang) # 显式加载rlang,也可以用rlang::前缀调用

describe_grp2 <- function(data, group){
  # 捕获裸变量为quosure对象
  egroup <- enquo(group)
  # 从quosure中提取变量名字符串
  group_name <- as_name(egroup)
  
  data %>% 
    tbl_summary(by = !!egroup) %>% # 展开quosure用于分组
    add_p() %>% 
    modify_caption(glue("Detection For **{group_name}**")) %>% # 使用变量名字符串生成标题
    bold_labels()
}

# 调用时直接用裸变量名
gapminder %>% 
  select(is.integer, is.double, continent) %>% 
  describe_grp2(group = continent)

方法2:ensym + {{}} 更简洁写法

ensym可以直接把裸变量(或字符串)转换成符号,再转成字符串,配合{{}}的插值语法更清爽:

describe_grp3 <- function(data, group){
  # 一步把裸变量转换为字符串
  group_name <- as_name(ensym(group))
  
  data %>% 
    tbl_summary(by = {{group}}) %>% # {{}}语法直接插值分组变量
    add_p() %>% 
    modify_caption(glue("Detection For **{group_name}**")) %>% 
    bold_labels()
}

# 调用方式完全不变
gapminder %>% 
  select(is.integer, is.double, continent) %>% 
  describe_grp3(group = continent)

为什么之前的代码会失败?

  • describe_grp2的问题:你直接在glue里写(!!egroup),这会把quosure展开成变量本身(比如continent这个因子对象),而不是变量名的字符串。glue会尝试对这个变量求值,最终显示的是因子的水平,而不是你想要的变量名。
  • describe_grp3的问题:三重花括号{{{group}}}是错误用法——glue的花括号和rlang的{{}}语法冲突了,这里并不能正确提取变量名,反而会导致glue解析错误或者显示混乱的内容。

额外小技巧:同时支持裸变量和字符串传参

如果想让函数兼容两种传参方式(裸变量/字符串),用ensym就可以轻松实现:

describe_grp4 <- function(data, group){
  group_name <- as_name(ensym(group))
  
  data %>% 
    tbl_summary(by = {{group}}) %>% 
    add_p() %>% 
    modify_caption(glue("Detection For **{group_name}**")) %>% 
    bold_labels()
}

# 两种调用方式都能正常工作
gapminder %>% 
  select(is.integer, is.double, continent) %>% 
  describe_grp4(group = continent) # 裸变量

gapminder %>% 
  select(is.integer, is.double, continent) %>% 
  describe_grp4(group = "continent") # 字符串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 20:42:29