如何计算数据框中各公司回答为Yes(1)的占比
按公司统计Yes回答占比实现方案
首先构造符合R语法的示例数据:
# 示例数据框 df <- data.frame( Company = c("a", "a", "b", "b", "b", "c", "c"), Response = c(1, 1, 2, 2, 1, 1, 2) )
以下提供两种常用实现方式:
方法1:Base R 无依赖实现
不需要安装第三方包,直接用R内置函数即可完成计算和格式化输出:
# 分组计算Yes(编码为1)的占比,结果取整 cal_result <- aggregate( Response ~ Company, data = df, FUN = function(x) round(sum(x == 1) / length(x) * 100, 0) ) # 按指定格式打印结果 cat('"yes" answers\n\n') apply(cal_result, 1, function(row) { cat(paste0("company ", row[["Company"]], " ", row[["Response"]], "%\n")) })
运行后输出完全匹配预期:
"yes" answers company a 100% company b 33% company c 50%
方法2:dplyr 实现(适合批量数据处理场景)
如果日常使用tidyverse生态处理数据,代码逻辑更简洁易读:
library(dplyr) df %>% group_by(Company) %>% # 计算每组Yes占比,取整后拼接%符号 summarise( yes_pct = paste0(round(sum(Response == 1) / n() * 100, 0), "%") ) %>% # 按要求格式输出 { cat('"yes" answers\n\n') pmap(., ~cat(paste0("company ", ..1, " ", ..2, "\n"))) }
内容的提问来源于stack exchange,提问作者glgp_col
相关产品推荐
相关产品推荐

