If I have a matrix:
mat=matrix(c(-21,14,28,17,-16,-9,-17,-30,18), nrow=3)
mat
[,1] [,2] [,3]
[1,] -21 17 17
[2,] 14 -16 -30
[3,] 28 -9 18
I can isolate the highest absolute value simply with
max(abs(mat))
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!
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
Building on Simon's answer. If you wanted a function that returned the absolute max for a vector or a matrix, you could use the following:
absmax <- function(x) { x[which.max( abs(x) )]}
E.g.,
> absmax(c(-10, 0, 9))
[1] -10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With