R function to find the vector with the highest correlation with all the remaining vectors

Viewed 403

I want to find which vector (or row) in a matrix has the highest correlation value to the other vectors (rows). Is there another solution than doing this in a loop like this :

mat <- matrix(rnorm(100), 5, 5)
for (i in 1:nrow(mat)){
  for (j in 1:nrow(mat)){
    # the correlation coefficients of each row
    cor_val[[i]][[j]] <- cor(mat[i,], mat[j,])
    # the average of the correlation coefficients of each row 
    cor_mean[[i]] <- mean(unlist(cor_val[[i]]))
  }
}

# the index of the row with the highest correlation
Indx <- which.max(cor_mean)
3 Answers

One approach is with cor. As pointed out by @Darren Tsai, cor calculates correlation by columns, but you can use t to transpose.

set.seed(3)
mat <- matrix(rnorm(100),5,5)

cor.mat <- cor(t(mat),t(mat))
max.cor <- max(abs(cor.mat[lower.tri(cor.mat)]))
which(abs(cor.mat) == max.cor, arr.ind = TRUE)
#     row col
#[1,]   3   2
#[2,]   2   3

Edit Forgot the call to abs in which, fixed.

From your loop code, the corresponding shorter version is

which.max(rowMeans(cor(t(mat))))

However, correlation coefficients can be positive or negative. Computing the average will balance the strength of correlation. I think it's better to compute the mean of absolute correlation or squared correlation. I.e.

which.max(rowMeans(abs(cor(t(mat)))))

or

which.max(rowMeans(cor(t(mat))^2))

You can just do cor(mat) to obtain a matrix of correlation indexes. Since Cor() returns the correlation between columns, you would have to first transpose your matrix.

mat <- matrix(rnorm(100),5,4)

mat <- t(mat)

cor(mat)
Related