如何传递gtsummary add_stat的location参数至自定义函数及手动传参?
解决gtsummary中add_stat的location参数传递与自定义函数参数指定问题
问题描述
我正在构建自定义函数,用于评估tbl_summary/tbl_svysummary中的组间成对差异。使用%>% add_stat(fns = everything() ~ custom_stat, location = ~"level")时,函数需返回行数等于分类变量水平数的df;使用location = ~"label"时需返回单行。但目前location参数未传递至自定义函数,请问如何获取该信息以适配输出?
附加问题:调用add_stat时能否手动为自定义函数指定额外参数(如loc)?
示例代码
library(tidyverse) library(gtsummary) print_one <- function(data, variable, by, tbl, loc = "label", ...) { if (loc == "label") { return(tibble(Res = 1)) } else { if (class(data[[variable]]) != "character" & class(data[[variable]]) != "factor" ) { return(tibble(Res = c())) } else { tibble(Res = 1:length(unique(data[[variable]]))) } } } trial %>% tbl_summary(by = trt, include = c(age, stage)) %>% add_stat(fns = everything() ~ print_one, location = ~ "level")
解决方案
1. 获取add_stat的location参数
add_stat的location参数会自动传递到自定义函数的...(可变参数)中,你可以从...里提取该参数值。修改自定义函数如下:
print_one <- function(data, variable, by, tbl, ...) { # 从可变参数中提取location,默认值设为"label" args <- list(...) loc <- if (is.null(args$location)) "label" else args$location if (loc == "label") { return(tibble(Res = 1)) } else { # 用inherits更简洁地判断变量类型 if (!inherits(data[[variable]], c("character", "factor"))) { return(tibble(Res = c())) } else { tibble(Res = 1:length(unique(data[[variable]]))) } } }
也可以使用gtsummary内置的%||%函数简化空值判断(该函数会返回第一个非空值):
loc <- args$location %||% "label"
修改后重新运行示例代码,函数就能根据add_stat指定的location返回对应结构的结果。
2. 手动为自定义函数指定额外参数
有两种方式可以手动给自定义函数传递额外参数:
方法一:使用purrr::partial绑定参数
通过purrr::partial预先为函数绑定参数值:
library(purrr) trial %>% tbl_summary(by = trt, include = c(age, stage)) %>% add_stat(fns = everything() ~ partial(print_one, loc = "custom_label"), location = ~ "level")
方法二:直接在公式中传递参数
gtsummary支持在fns的公式里直接指定函数参数:
trial %>% tbl_summary(by = trt, include = c(age, stage)) %>% add_stat(fns = everything() ~ print_one(loc = "custom_label"), location = ~ "level")
这种方式会覆盖从location参数获取的值,或为函数补充其他自定义参数。
内容的提问来源于stack exchange,提问作者ZKA
相关产品推荐
相关产品推荐

