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

如何以列a为基准计算每行b、c列的百分比?优先用tidyverse方法

使用tidyverse计算列占比(以a列为基准)

实现思路

通过dplyr的mutate()函数新增计算列,核心逻辑是每行的b/c值除以对应行的a值,再乘以100得到占比百分比。若需要匹配预期输出的小数位数,可搭配round()函数控制精度。

完整代码

library(tidyverse)

# 构建示例数据集
c <- c(10, 20, 30, 40, 50)
b <- c(40, 2, 40, 10, 50)
a <- c(100, 50, 70, 60, 100)
id <- c("a", "b", "c", "d", "e")

data <- data.frame(id, a, b, c)

# 计算占比并保留4位小数
result <- data %>%
  mutate(
    proportion_b = round((b / a) * 100, 4),
    proportion_c = round((c / a) * 100, 4)
  )

# 查看结果
print(result)

输出结果

#    id   a  b  c proportion_b proportion_c
# 1  a 100 40 10            40           10
# 2  b  50  2 20             4           40
# 3  c  70 40 30      57.1429     42.8571
# 4  d  60 10 40      16.6667     66.6667
# 5  e 100 50 50            50           50

补充说明

  • 若无需限制小数位数,直接移除round()函数即可,R会保留原始计算精度
  • 该方法为逐行运算,完全满足以a列为每行基准的计算需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:27:36