基于tbl_summary按Category和Result统计唯一ID计数的问题
问题与解决方案
原始长表示例
| ID | Gene | Result | Category |
|---|---|---|---|
| 1 | BRCA1 | Pos | Tissue |
| 1 | ATM | Pos | Tissue |
| 2 | BRCA1 | Neg | Liquid |
| 2 | ATM | Neg | Tissue |
| 3 | BRCA1 | Pos | Liquid |
需求
生成按Category和Result分组的汇总表,所有统计均基于唯一ID计数(而非原始行计数)。
现有代码问题
原代码实现了双变量分层统计,但顶部的N(Liquid)/N(Tissue)显示全量ID数,正负结果统计的是行数,未实现两类统计均按唯一ID计数,且存在拼写错误。
原代码:
Genes%>% select (Gene, Result,Category)%>% mutate (Category=paste("Category",Category))%>% tbl_strata( strata=testcategory, .tbl_fun= ~.x%>% tbl_summary(by=Result,missing="no")%>% add_n(group_by(Genes$Category)), .header="**{strata}**, N={n_distinct(Genese$ID)}" )
优化后代码
方案1:先去重再统计
先预处理数据,保留每个ID-Category-Result的唯一组合,再进行统计:
# 预处理:去重,确保每个ID在同一Category+Result下仅算一次 Genes_unique <- Genes %>% distinct(ID, Category, Result, .keep_all = FALSE) %>% mutate(Category = paste("Category", Category)) # 生成汇总表 Genes_unique %>% tbl_strata( strata = Category, .tbl_fun = ~ .x %>% tbl_summary( by = Result, missing = "no", statistic = all_categorical() ~ "{n}" ) %>% add_n(), .header = "**{strata}**, N={n}" )
方案2:直接在统计中指定唯一ID计数
无需预处理,在tbl_summary中直接用n_distinct(ID)统计:
Genes %>% mutate(Category = paste("Category", Category)) %>% tbl_strata( strata = Category, .tbl_fun = ~ .x %>% tbl_summary( by = Result, missing = "no", statistic = ~"{n_distinct(ID)}" ) %>% modify_header(all_stat_cols() ~ "**{level}** (n={n_distinct(ID)})") %>% add_n(n = n_distinct(.x$ID)), .header = "**{strata}**, N={n_distinct(.x$ID)}" )
优化说明
- 修正原代码拼写错误:
Genese改为Genes,testcategory改为Category - 两种方案均通过
n_distinct(ID)确保统计的是唯一ID数量,而非原始行数 - 方案1通过去重减少计算量,方案2直接在统计函数中指定,更灵活
内容的提问来源于stack exchange,提问作者Danielle
相关产品推荐
相关产品推荐

