brown_squirrel
brown_squirrel

Reputation: 83

Return Column and Row name of largest correlation pair, correlation martix in R

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!

Upvotes: 1

Views: 225

Answers (3)

Annie Chen
Annie Chen

Reputation: 61

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)

Upvotes: 2

Jan
Jan

Reputation: 5254

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)

Upvotes: 1

Matt
Matt

Reputation: 7385

You can do:

max(sort(cor_mat[cor_mat != 1]))

Which gives us:

[1] 0.7

Upvotes: 0

Related Questions