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

求助:基于R语言数据框生成吃过食物人群的过敏占比统计表格

问题描述

原始数据框如下(1代表“是”,0代表“否”):

ever_eaten_banana <- c(1,1,0,0)
allergic_banana <- c(1,0,1,0)
ever_eaten_shellfish <- c(0,1,1,1)
allergic_shellfish <- c(0,1,0,0)

df <- data.frame(ever_eaten_banana,allergic_banana,ever_eaten_shellfish,allergic_shellfish)

数据预览:

ever_eaten_banana allergic_banana ever_eaten_shellfish allergic_shellfish
1                 1               1                    0                  0
2                 1               0                    1                  1
3                 0               1                    1                  0
4                 0               0                    1                  0

需求:生成统计表格,展示吃过每种食物的人群中对该食物过敏的百分比,需排除未吃过该食物却自称过敏的人群。例如香蕉有2人吃过,其中1人过敏,占比50%;贝类有3人吃过,其中1人过敏,占比33%。期望输出表格:

食物占比
Bananas50%
Shellfish33%
解决方案

方法1:基础R实现

针对每种食物单独筛选计算,再合并结果:

# 筛选吃过香蕉的人群,计算过敏占比
banana_eaters <- df[df$ever_eaten_banana == 1, ]
banana_allergy_pct <- round(mean(banana_eaters$allergic_banana) * 100)

# 筛选吃过贝类的人群,计算过敏占比
shellfish_eaters <- df[df$ever_eaten_shellfish == 1, ]
shellfish_allergy_pct <- round(mean(shellfish_eaters$allergic_shellfish) * 100)

# 整理成目标表格
result_df <- data.frame(
  食物 = c("Bananas", "Shellfish"),
  占比 = paste0(c(banana_allergy_pct, shellfish_allergy_pct), "%")
)

print(result_df)

运行输出:

食物  占比
1   Bananas  50%
2 Shellfish  33%

方法2:tidyverse框架实现(适合多食物扩展)

如果后续需要添加更多食物,将宽数据转为长格式处理更高效,无需重复编写筛选逻辑:

library(tidyverse)

# 转换为长格式,统一食物列名
long_df <- df %>%
  pivot_longer(
    cols = everything(),
    names_to = c(".value", "food"),
    names_pattern = "(ever_eaten|allergic)_(.*)"
  ) %>%
  mutate(food = str_to_title(food))

# 按食物分组,计算吃过人群的过敏占比
result_df <- long_df %>%
  filter(ever_eaten == 1) %>% # 仅保留吃过该食物的样本
  group_by(food) %>%
  summarise(
    占比 = paste0(round(mean(allergic) * 100), "%")
  ) %>%
  rename(食物 = food)

print(result_df)

运行结果与方法1一致,且新增食物列时,只要列名符合ever_eaten_xxx和allergic_xxx的命名规则,代码无需修改即可自动计算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 23:16:00