Edward Armstrong - 5 months ago 34

R Question

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!

Answer

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
```