Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the maximum absolute value whilst preserving + or - symbol

Tags:

r

matrix

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!

like image 682
Edward Armstrong Avatar asked Jul 09 '14 11:07

Edward Armstrong


2 Answers

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
like image 90
Simon O'Hanlon Avatar answered Nov 07 '22 10:11

Simon O'Hanlon


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
like image 9
Jeromy Anglim Avatar answered Nov 07 '22 10:11

Jeromy Anglim