Correlation between two matrices of different dimensions

Viewed 571

I'm very new to R. I have two matrices of different dimensions, C (3 rows, 79 columns) and T(3 rows, 215 columns). I want my code to calculate the Spearman correlation between the first column of C and all the columns of T and return the maximum correlation with the indexes and of the columns. Then, the second column of C and all the columns of T and so on. In fact, I want to find the columns between two matrices which are most correlated. Hope it was clear. What I did was a nested for loop, but the result is not what I search.

for (i in 1:79){
    for(j in 1:215){
        print(max(cor(C[,i],T[,j],method = c("spearman"))))
  }
}
2 Answers

You don't have to loop over the columns.

x <- cor(C,T,method = c("spearman"))

out <- data.frame(MaxCorr = apply(x,1,max), T_ColIndex=apply(x,1,which.max),C_ColIndex=1:nrow(x))

head(out)

gives,

  MaxCorr T_ColIndex C_ColIndex
1       1          8          1
2       1          1          2
3       1          2          3
4       1          1          4
5       1         11          5
6       1          4          6

Fake Data:

C <- matrix(rnorm(3*79),nrow=3)
T <- matrix(rnorm(3*215),nrow=3)

Maybe something like the function below can solve the problem.

pairwise_cor <- function(x, y, method = "spearman"){
  ix <- seq_len(ncol(x))
  iy <- seq_len(ncol(y))
  t(sapply(ix, function(i){
    m <- sapply(iy, function(j) cor(x[,i], y[,j], method = method))
    setNames(c(i, which.max(m), max(m)), c("col_x", "col_y", "max"))
  }))
}

set.seed(2021)
C <- matrix(rnorm(3*5), nrow=3)
T <- matrix(rnorm(3*7), nrow=3)

pairwise_cor(C, T)
#     col_x col_y max
#[1,]     1     1 1.0
#[2,]     2     2 1.0
#[3,]     3     2 1.0
#[4,]     4     3 0.5
#[5,]     5     5 1.0
Related