繁体   English   中英

R 循环:每 12 行执行一次 spearman 相关

[英]R Loop: Perform a spearman correlation for Every 12 Rows

我有一个包含 984 行和 2 列(M 和 B)的矩阵,我想对每 12 行的 2 列进行 spearman 相关,因此总共有 82 个相关。 这就是我所拥有的

df ->read(......)
M = df$M
B = df$B

cnt <- 0
for (i in seq(1, nrow(df), by = 12)) {
M = df$[M,cnt]
B = df$[B, cnt]
resultM-B = cor(M, B, method = "spearman")
cat("Spearman correlation MB", resultM-B,"\n")
cnt <- cnt + 12
}

谢谢

看起来像一个by

构成索引因子

idx <- ceiling((1:nrow(df))/12)

然后告诉by使用它作为指南:

res <- by(df, idx, function(x){cor(x$M, x$B, method ="spearman")})

对于 24 行的虚拟数据,您可以尝试

df1 <- data.frame(
  M = rnorm(24, 1, 1),
  B = rnorm(24, 1, 5)
)

cnt <- 12
res <- c()
for (i in seq(1, nrow(df1), by = 12)){
  M1 <- df1$M[i:cnt]
  B1 <- df1$B[i:cnt]
  res_MB <- cor(M1, B1, method = "spearman")
  res <- c(res, res_MB)
  cnt <- cnt + 12
}
res
[1] -0.4755245 -0.2727273

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM