如何在R中按id分组计算numbers变量的占比?(基础版与dplyr版)
问题描述
给定如下数据集:
numbers <- c(10, 50, 3, 60, 100,40, 2, 40, 10, 50) id <- c("a", "a", "a", "a", "b", "b", "b", "b", "c", "c") variation <- c("type1", "type2", "type2", "type3", "type1","type2", "type3", "type3", "type2", "type2" ) data <- data.frame(id, numbers, variation)
需求:按id分组,计算每组内每个numbers值的占比,生成名为percent的变量。
方法一:R基础语法实现
利用ave()函数按组计算总和,再推导占比:
# 按id分组计算每组numbers的总和 group_sums <- ave(data$numbers, data$id, FUN = sum) # 计算百分比并添加为新列 data$percent <- (data$numbers / group_sums) * 100 # 查看结果 print(data)
方法二:dplyr包实现
先确保安装并加载dplyr包,再通过分组+突变操作完成计算:
# 若未安装dplyr则先执行安装 # install.packages("dplyr") library(dplyr) data <- data %>% group_by(id) %>% mutate(percent = (numbers / sum(numbers)) * 100) %>% ungroup() # 查看结果 print(data)
内容的提问来源于stack exchange,提问作者choij
相关产品推荐
相关产品推荐

