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

如何基于分组计数计算各国死亡率变量?(dplyr实现)

解决方案:计算各国死亡率并识别异常值国家

步骤1:数据整理与死亡率计算

结合你提到的dplyr函数,这里提供两种贴合需求的实现方式:

方式一:直接分组计算(更简洁)

假设death_rate是数值型二分类变量(1=死亡,0=存活),代码如下:

library(dplyr)

# 筛选列、排除缺失值、分组计算死亡率
mortality_summary <- df_incl_countries_with_outliers %>%
  select(Country, death_rate) %>%
  filter(!is.na(death_rate)) %>%  # 排除死亡状态缺失的样本
  group_by(Country) %>%
  mutate(
    total_samples = n(),  # 该国有效总样本数
    death_count = sum(death_rate, na.rm = TRUE)  # 统计死亡人数
  ) %>%
  mutate(mortality = death_count / total_samples) %>%  # 计算死亡率
  distinct(Country, mortality, total_samples, death_count)  # 去重,保留每个国家的唯一汇总行

如果death_rate是字符型(比如"Dead"/"Alive"),先转成数值再计算:

mortality_summary <- df_incl_countries_with_outliers %>%
  select(Country, death_rate) %>%
  filter(!is.na(death_rate)) %>%
  mutate(death_rate = ifelse(death_rate == "Dead", 1, 0)) %>%  # 转成数值型二分类
  group_by(Country) %>%
  mutate(
    total_samples = n(),
    death_count = sum(death_rate, na.rm = TRUE)
  ) %>%
  mutate(mortality = death_count / total_samples) %>%
  distinct(Country, mortality, total_samples, death_count)

方式二:先分组计数再计算(贴合你提到的count()函数)

先通过count()得到各国死亡/存活的分组计数,再汇总计算死亡率:

mortality_summary <- df_incl_countries_with_outliers %>%
  select(Country, death_rate) %>%
  filter(!is.na(death_rate)) %>%
  count(Country, death_rate, name = "group_count") %>%  # 统计各国死亡/存活的人数
  group_by(Country) %>%
  mutate(total_samples = sum(group_count)) %>%  # 计算该国总样本数
  filter(death_rate == 1) %>%  # 仅保留死亡组数据
  mutate(mortality = group_count / total_samples) %>%  # 计算死亡率
  select(Country, mortality, total_samples, death_count = group_count)

步骤2:绘制箱线图识别异常值国家

使用ggplot2绘制箱线图,红色点即为异常值国家,还可以添加标签直接显示国家名称:

library(ggplot2)

# 基础箱线图
ggplot(mortality_summary, aes(x = "", y = mortality)) +
  geom_boxplot(fill = "lightblue", outlier.color = "red", outlier.size = 3) +
  labs(title = "各国死亡率分布", y = "死亡率", x = "") +
  theme_minimal()

# 标注异常值国家名称的箱线图
ggplot(mortality_summary, aes(x = "", y = mortality)) +
  geom_boxplot(fill = "lightblue", outlier.color = "red", outlier.size = 3) +
  # 仅给异常值添加国家标签
  geom_text(aes(label = ifelse(mortality %in% boxplot.stats(mortality)$out, Country, "")),
            hjust = -0.1, vjust = 0, color = "darkred") +
  labs(title = "各国死亡率分布(标注异常值国家)", y = "死亡率", x = "") +
  theme_minimal() +
  coord_flip()  # 翻转坐标轴,避免标签重叠

说明

  • 所有代码均已排除death_rate的缺失值,确保计算的死亡率基于有效样本。
  • 箱线图的异常值判定基于默认的四分位距(IQR)规则:超出Q3 + 1.5*IQR或Q1 - 1.5*IQR的数值会被标记为异常值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 15:47:38