I have a matrix which contains 984 rows and 2 columns (M and B), I want to do a spearman correlation of the 2 columns for every 12 rows, so in total 82 correlation. This is what I have
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
}
Thanks
CodePudding user response:
Looks like a job for by
Make up an indexing factor
idx <- ceiling((1:nrow(df))/12)
Then tell by
to use that as a guide:
res <- by(df, idx, function(x){cor(x$M, x$B, method ="spearman")})
CodePudding user response:
For dummy data with 24 rows, you may try
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