如何在R语言数据框中逐行计算Spearman相关系数?
问题描述
我有一个包含列表列的数据框,前四行数据生成代码如下:
X1 <- list(c(1, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5), c(1.5, 1.5, 5, 5, 5, 5, 5), c(1, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5), c(1, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5)) X2 <- list(c(1, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5), c(1, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5), c(1.5, 1.5, 5, 5, 5, 5, 5), c(1, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5)) # 生成数据框 all_comb <- data.frame(X1 = I(X1), X2 = I(X2))
需求是为每行计算Spearman秩相关系数,例如对第一行执行:
cor.test(c(1, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5), c(1.5, 1.5, 5, 5, 5, 5, 5), method = "spearman")$estimate
并将计算得到的rho值存入数据框的新列中。
尝试了以下代码,但报错x must be a numeric vector:
b = apply(all_comb, 1, function(x) { cor.test(all_comb, x, method = "spearman") })
错误原因
apply处理数据框时,会将每行的列表列强制转换为普通向量,破坏了原有的列表结构,导致cor.test无法识别正确的输入。- 代码参数使用错误:
cor.test(all_comb, x)第一个参数传入了整个数据框,而非当前行的X1列表;第二个参数x也不是目标的X2列表。
解决方案
以下是几种可行的实现方式:
方法1:用dplyr逐行处理
library(dplyr) all_comb <- all_comb %>% rowwise() %>% mutate(spearman_rho = cor.test(X1, X2, method = "spearman")$estimate) %>% ungroup()
方法2:用mapply批量处理列表列
all_comb$spearman_rho <- mapply(function(x, y) { cor.test(x, y, method = "spearman")$estimate }, all_comb$X1, all_comb$X2)
方法3:用purrr的map2函数
library(purrr) all_comb$spearman_rho <- map2_dbl(all_comb$X1, all_comb$X2, ~cor.test(.x, .y, method = "spearman")$estimate)
结果验证
运行上述代码后,数据框会新增spearman_rho列,存储每行的Spearman相关系数。示例数据的前四行结果均为1(完全正相关)。
内容的提问来源于stack exchange,提问作者other
相关产品推荐
相关产品推荐

