I'm trying to return the maximum value and its column, row in a correlation matrix in R using this line of code. The correlation matrix is called cor_mat and I don't want to include the values that = 1 because those are variables' correlation with themselves.
This is my matrix
cor_mat.data <- c(1.00, 0.70,0.31,0.11,0.70,1.00,0.19,0.07,0.31,0.19,1.00,0.45,0.11,0.07,0.45,1.00)
cor_mat <- matrix(cor_mat.data, nrow=4,ncol=4,byrow=TRUE)
and this is what I've been trying:
which(abs(cor_mat) == max(cor_mat) && abs(cor_mat) != 1, arr.ind = TRUE)
Any advice is greatly appreciated!
CodePudding user response:
Are you looking for this?
maximum value in matrix:
max(abs(cor_mat[upper.tri(cor_mat)]))
index/indices of maximum(s):
which(cor_mat == max(abs(cor_mat[upper.tri(cor_mat)])), arr.ind = T)
CodePudding user response:
We have to make sure that we keep correlations that are 1 but aren’t located in the diagonal where the correlations of variables with themselves are located.
With upper.tri
we can filter all values of the diagonal and the lower triangle (because values in upper and lower triangle are the same by definition).
cor_mat.data <- c(1.00, 0.70,0.31,0.11,0.70,1.00,0.19,0.07,0.31,0.19,1.00,0.45,0.11,0.07,0.45,1.00)
cor_mat <- matrix(cor_mat.data, nrow=4,ncol=4,byrow=TRUE)
MaxVal <- max(abs(cor_mat[upper.tri(cor_mat)]))
which(abs(cor_mat) == MaxVal, arr.ind = TRUE)
#> row col
#> [1,] 2 1
#> [2,] 1 2
Created on 2021-10-14 by the reprex package (v2.0.1)
CodePudding user response:
You can do:
max(sort(cor_mat[cor_mat != 1]))
Which gives us:
[1] 0.7