Finding row index containing maximum value using R

后端 未结 3 1768
醉话见心
醉话见心 2020-11-30 23:28

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条回答
  • 2020-12-01 00:12

    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]
    
    0 讨论(0)
  • 2020-12-01 00:14

    See ?which.max

    > which.max( matrix[,2] )
    [1] 2
    
    0 讨论(0)
  • 2020-12-01 00:25

    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.

    0 讨论(0)
提交回复
热议问题