Edward Armstrong Edward Armstrong - 1 year ago 69
R Question

Finding the maximum absolute value whilst preserving + or - symbol

If I have a matrix:

mat=matrix(c(-21,14,28,17,-16,-9,-17,-30,18), nrow=3)
[,1] [,2] [,3]
[1,] -21 17 17
[2,] 14 -16 -30
[3,] 28 -9 18

I can isolate the highest absolute value simply with


However how do I preserve the sign so I return -30?
For some context, I have a large number of matrices and I need a command to isolate the highest absolute number in all of them including the sign (some will be positive others negative).

Thanks in advance!

Answer Source

You need the index of the value in the matrix which is the maximum absolute value, which you can then use to return the value itself. which.max will do this (and which.min for the opposite):

mat[which.max( abs(mat) )]
# [1] -30
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download