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

如何基于虚拟变量在R中生成比例DataFrame并绘制柱状图?

简洁计算分类变量1的占比并绘制柱状图(R语言)

嘿,我有个超简洁的方案帮你搞定这个需求,比你现在用的dplyr分组统计要高效太多啦!核心思路是利用0-1编码变量的均值就是1的占比这个特性,一步就能算出结果,完全不用繁琐的分组统计~


第一步:快速生成占比DataFrame

先模拟你的示例数据:

# 模拟你的原始数据
df <- data.frame(
  ID = 1:3,
  category1 = c(1,0,1),
  category2 = c(0,0,1),
  category3 = c(1,0,1),
  category4 = c(0,0,0),
  category5 = c(0,0,0)
)

接下来用一行核心代码算出占比,再整理成你想要的格式:

library(dplyr)
library(scales)

# 计算占比并格式化
proportion_df <- df %>%
  select(starts_with("category")) %>% # 精准选中所有分类列
  colMeans() %>% # 直接计算每列1的占比(0-1变量的均值就是1的比例)
  t() %>% # 转置成行的形式
  as.data.frame() %>%
  mutate(across(everything(), ~percent(., accuracy = 0.01))) %>% # 转成带两位小数的百分比
  `rownames<-`("proportion") # 设置行名

# 查看结果
proportion_df

运行后输出完全符合你的要求:

category1 category2 category3 category4 category5
proportion     66.67%    33.33%    66.67%      0.00%      0.00%

如果不想用dplyr,纯基础R也能实现:

# 基础R版本
category_cols <- grep("category", names(df), value = TRUE)
proportions <- colMeans(df[category_cols])
proportion_df_base <- data.frame(t(proportions))
proportion_df_base[] <- lapply(proportion_df_base, function(x) percent(x, accuracy = 0.01))
rownames(proportion_df_base) <- "proportion"

第二步:绘制柱状图

我们需要先把宽格式的占比数据转成长格式(tidy data),再用ggplot2绘制:

library(ggplot2)
library(tidyr)

# 转成长格式(用于绘图)
proportion_long <- proportion_df %>%
  rownames_to_column() %>%
  pivot_longer(-rowname, names_to = "category", values_to = "proportion") %>%
  mutate(proportion = as.numeric(sub("%", "", proportion))/100) # 把百分比转成数值

# 绘制柱状图
ggplot(proportion_long, aes(x = category, y = proportion)) +
  geom_bar(stat = "identity", fill = "#2E86AB", alpha = 0.8) +
  scale_y_continuous(labels = percent) + # Y轴显示百分比格式
  labs(x = "类别", y = "1的占比", title = "各分类变量中1的占比分布") +
  theme_minimal()

这样就能得到X轴为类别、Y轴为占比的清晰柱状图啦~


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:34:57