Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find row and column index of maximum value in a matrix [duplicate]

Tags:

r

matrix

I wish to find the maximum element-value of a matrix and it's location (in row and column id in the matrix).

I am using the following function to return the row and column of the matrix.

This seems like a bad hack -- it's the sort of thing where i'm probably missing a native method. Is there a better / more R way?

Here's my function:

matxMax <- function(mtx) {     colmn <- which(mtx == max(mtx)) %/% nrow(mtx) + 1     row <- which(mtx == max(mtx)) %% nrow(mtx)     return( matrix(c(row, colmn), 1)) } 

I use is as follows:

mm <- matrix(rnorm(100), 10, 10) maxCords <- matxMax(mm) mm[maxCords] 
like image 230
ricardo Avatar asked Jul 12 '13 03:07

ricardo


People also ask

What is the command to find maximum and minimum values in a column row or matrix?

We have made use of the max() function which is used to find the maximum element present in an object. This object can be a Vector, a list, a matrix, a data frame, etc. The “which()” function is used to get the index or position of the value which satisfies the given condition.

How do you find the maximum index of a matrix?

In case of a 2D array (matrix), you can use: [val, idx] = max(A, [], 2); The idx part will contain the column number of containing the max element of each row.

How do you find the index of a maximum value in R?

We can find the maximum value index in a dataframe using the which. max() function. “$” is used to access particular column of a dataframe.

How do you find the maximum value of a matrix in R?

max() in R The max() is a built-in R function that finds the maximum value of the vector or data frame. It takes the R object as an input and returns the maximum value out of it. To find the maximum value of vector elements, data frame, and columns, use the max() function.


1 Answers

You could do

## Some data set.seed(123) mm <- matrix(rbinom(40, 20, 0.5), 8, 5) mm #      [,1] [,2] [,3] [,4] [,5] # [1,]    9   10    8   11   11 # [2,]   12   10    6   11   12 # [3,]    9   14    9   10    6 # [4,]   13   10   14   11   10 # [5,]   13   11   13    9   12 # [6,]    6   10   11    8    8 # [7,]   10    7   11   14    9 # [8,]   13   13   16   13    8  which(mm == max(mm), arr.ind = TRUE) #      row col # [1,]   8   3 
like image 139
QuantIbex Avatar answered Oct 15 '22 01:10

QuantIbex