Jared
Jared

Reputation: 39877

Finding row index containing maximum value using R

Given the following matrix lets assume I want to find the maximum value in column two:

mat <- matrix(c(1:3,7:9,4:6), byrow = T, nc = 3)
mat
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    7    8    9
[3,]    4    5    6

I know max(mat[,2]) will return 8. How can I return the row index, in this case row two?

Upvotes: 132

Views: 171527

Answers (5)

Karolis Koncevičius
Karolis Koncevičius

Reputation: 9656

There is a function max.col(). For every row it finds which column has the maximum value:

max.col(mat)
[1] 3 3 3

To find the maximum row for each column instead, simply transpose the matrix:

max.col(t(mat))
[1] 2 2 2

Upvotes: 1

rubengavidia0x
rubengavidia0x

Reputation: 590

A different way using dplyr:

mat <- matrix(c(1:3,7:9,4:6), byrow = T, nc = 3)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    7    8    9
[3,]    4    5    6

mat %>% as_tibble() %>% filter( V2 == max(V2) )

# A tibble: 1 x 3
     V1    V2    V3
  <int> <int> <int>
1     7     8     9

Upvotes: 1

QFanatic
QFanatic

Reputation: 31

How about the following, where y is the name of your matrix and you are looking for the maximum in the entire matrix:

row(y)[y==max(y)]

if you want to extract the row:

y[row(y)[y==max(y)],] # this returns unsorted rows.

To return sorted rows use:

y[sort(row(y)[y==max(y)]),]

The advantage of this approach is that you can change the conditional inside to anything you need. Also, using col(y) and location of the hanging comma you can also extract columns.

y[,col(y)[y==max(y)]]

To find just the row for the max in a particular column, say column 2 you could use:

seq(along=y[,2])[y[,2]==max(y[,2])]

again the conditional is flexible to look for different requirements.

See Phil Spector's excellent "An introduction to S and S-Plus" Chapter 5 for additional ideas.

Upvotes: 3

Danko Durbić
Danko Durbić

Reputation: 7237

See ?which.max

> which.max( matrix[,2] )
[1] 2

Upvotes: 187

yoyoyoyosef
yoyoyoyosef

Reputation: 7228

See ?order. You just need the last index (or first, in decreasing order), so this should do the trick:

order(matrix[,2],decreasing=T)[1]

Upvotes: 29

Related Questions