簡體   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