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

使用dplyr计算多分组下实验组相对对照组的百分比差异

解决方案

使用dplyr包可以快速实现需求,核心逻辑是按name和type分组后,提取对照组与实验组的数值,再计算相对百分比变化。

数据加载

先将你的数据导入R环境:

df <- structure(list(name = c("A", "A", "A", "A", "A", "A", "B", "B", 
"B", "B", "B", "B", "C", "C", "C", "C", "C", "C"), value = c(1.19836644827586, 
2.46856144477028, 0.856237188191882, 0.778078289325843, 0.59811550273224, 
0.787017526104418, 0.473075959100205, 1.11257028100264, 3.53950002293968, 
3.25319619936034, 0.514323313099042, 0.58826350129199, 3.38210735688006, 
3.78537735596708, 0.917653452784504, 0.753012044982699, 6.84112906311637, 
6.27268644079398), exp = c("control", "experiment", "control", 
"experiment", "control", "experiment", "control", "experiment", 
"control", "experiment", "control", "experiment", "control", 
"experiment", "control", "experiment", "control", "experiment"
), type = c("typeA", "typeA", "typeB", "typeB", "typeC", "typeC", 
"typeA", "typeA", "typeB", "typeB", "typeC", "typeC", "typeA", 
"typeA", "typeB", "typeB", "typeC", "typeC")), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -18L))

计算百分比变化

通过分组汇总完成计算:

library(dplyr)

result <- df %>%
  group_by(name, type) %>%
  summarize(
    percentage_change = (value[exp == "experiment"] - value[exp == "control"]) / value[exp == "control"] * 100,
    .groups = "drop"
  ) %>%
  mutate(percentage_change = round(percentage_change, 2))

print(result)

输出结果

运行代码后会得到与你期望一致的结果:

# A tibble: 9 × 3
  name  type  percentage_change
  <chr> <chr>             <dbl>
1 A     typeA              106. 
2 A     typeB              -9.13
3 A     typeC              31.6 
4 B     typeA              135. 
5 B     typeB              -8.09
6 B     typeC              14.4 
7 C     typeA              11.9 
8 C     typeB             -17.9 
9 C     typeC              -8.31

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 07:24:25