R语言中简化多方法排名生成与Spearman相关性计算的方法
简化Spearman系数分析的实现方式
需求说明
原代码通过4条独立命令生成各方法的排名,再筛选列计算排名间的Spearman系数,希望实现更简洁的批量处理流程。
优化后的代码
library(dplyr) # 原始数据 padr <- structure(list(Method1= c(0.343394182514031, 1, 0.860087696840587, 0.860087696840587, 0.868085451239441, 0.698055447477473, 0.43737803420133, 0.434970400304271, 0.434970400304271, 0.379233994071699), Method2 = c(1, 0.232979733215734, 0.240392548713602, 0.240392548713602, 0.213384133751235, 0.240137915565427, 0.321393780370283, 0.322481353908317, 0.322481353908317, 0.352233249467427), Method3 = c(1, 0.214432400448801, 0.214809476505306, 0.214809476505306, 0.16783443847331, 0.210797750473198, 0.293103343189013, 0.293692283587016, 0.293692283587016, 0.281085590908947), Method4 = c(0, 1, 0.875556823046433, 0.875556823046433, 0.891768819029077, 0.832271929255291, 0.741168314099481, 0.740578512687553, 0.740578512687553, 0.819053554576837 )), class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10")) # 链式操作完成排名生成与Spearman系数计算 padr %>% # 批量生成排名列,按需求指定不同的ties.method mutate( RankMethod1 = (n() + 1) - rank(Method1, ties.method = "last"), across(c(Method2, Method3), ~(n() + 1) - rank(., ties.method = "first"), .names = "Rank{.col}"), RankMethod4 = (n() + 1) - rank(Method4, ties.method = "last") ) %>% # 自动匹配所有排名列,计算与RankMethod1的Spearman系数 summarise(across(starts_with("Rank"), ~cor.test(., RankMethod1, method = "spearman")$estimate))
优化点说明
- 用
across批量处理Method2、Method3的排名生成,减少重复代码 - 用
starts_with("Rank")自动匹配所有排名列,无需手动指定列索引或范围 - 全程链式操作,无需中间筛选列的步骤,代码更简洁流畅
输出结果
RankMethod1 RankMethod2 RankMethod3 RankMethod4 1 1 -0.9515152 -0.830303 0.9272727
内容的提问来源于stack exchange,提问作者Antonio
相关产品推荐
相关产品推荐

