R语言tidyverse 如何按受害伤情分组计算酒精涉入两类的N比值
基于tidyverse的分组比值计算实现
你可以直接在现有预处理得到的计数结果上追加计算逻辑,不需要额外做复杂的格式转换,两种常用写法均可实现目标:
方法1:长表转宽表直接计算
这个写法逻辑最直观,先把每个受伤程度分组下的NO/YES计数拆成独立列,再直接做除法:
library(tidyverse) # 对应你提供dput结构的计数数据 count_df <- structure(list(alcohol_involved = c("NO", "YES", "NO", "YES", "NO", "YES", "NO", "YES", "NO", "YES"), victim_degree_of_injury = c("complaint of pain", "complaint of pain", "killed", "killed", "no injury", "no injury", "other visible injury", "other visible injury", "severe injury", "severe injury"), N = c(16516L, 1331L, 168L, 122L, 22860L, 1905L, 4778L, 1102L, 752L, 315L)), class = "data.frame", row.names = c(NA, -10L)) ratio_result <- count_df %>% # 拆分NO/YES为独立的计数列 pivot_wider(names_from = alcohol_involved, values_from = N) %>% # 计算同组内YES计数 / NO计数的比值 mutate(alcohol_involved_ratio = YES / NO)
方法2:分组内直接取数计算
不需要转换宽表格式,直接在每个受伤程度分组内按条件提取对应的N值做除法,计算结果和方法1完全一致:
ratio_result_alt <- count_df %>% group_by(victim_degree_of_injury) %>% reframe( yes_count = N[alcohol_involved == "YES"], no_count = N[alcohol_involved == "NO"], alcohol_involved_ratio = yes_count / no_count )
现有数据的计算结果
按当前数据集算出来的各组比值如下:
- complaint of pain:
1331 / 16516 ≈ 0.081 - killed:
122 / 168 ≈ 0.726 - no injury:
1905 / 22860 ≈ 0.083 - other visible injury:
1102 / 4778 ≈ 0.231 - severe injury:
315 / 752 ≈ 0.419
全流程优化写法
你之前的预处理代码混用了as.data.table()和dplyr的分组逻辑,其实可以全程用tidyverse内置函数把计数、比值计算串成一条连续管道,省掉不同包之间的格式转换步骤:
col_vict %>% select(alcohol_involved, victim_degree_of_injury) %>% mutate(alcohol_involved = as.factor(ifelse(is.na(alcohol_involved), "NO", "YES"))) %>% # 用count()生成分组计数,替代table()转格式的繁琐步骤 count(alcohol_involved, victim_degree_of_injury, name = "N") %>% pivot_wider(names_from = alcohol_involved, values_from = N) %>% mutate(alcohol_involved_ratio = YES / NO)
小提示:之前的预处理代码写到
group_by(victim_degree_of_injury)就中断了,此时生成的是带分组属性的临时tibble,没有绑定到实际存储对象上,后续直接操作容易出现分组残留导致的计算错误。
内容的提问来源于stack exchange,提问作者CelineDion
相关产品推荐
相关产品推荐

