使用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
相关产品推荐
相关产品推荐

