Get indices of K smallest or largest elements in each row of a matrix in R
Asked Answered
P

2

8

How to get indices of K smallest or largest elements in eaach row of a matrix in R?

E.g. I have matrix:

2   3   1  65  2
46  7   9  3   2
9   45  3  5   7
24  65  87 3   6
34  76  54 33  6

I'd like to get Indices matrix of say 2 smallest elements (breaking ties in any way) in each row. the result should be in following format:

3 1
5 4
3 4
4 5
5 4

I tried few commands using sort, apply, arrayInd, which etc. But still unable to get desired result. Any help is welcome.

Prelusive answered 24/12, 2012 at 6:6 Comment(0)
E
13
apply(mat, 1, which.max)  #.....largest
apply(mat, 1, which.min)  #.....smallest

t(apply(mat, 1, sort)[ 1:2, ])  # 2 smallest in each row

t(apply(mat, 1, order)[ 1:2, ])  # indices of 2 smallest in each row

Besides using decreasing=TRUE, you could also have used this for the two largest in a row:

t(apply(mat, 1, order)[ 5:4, ])    
Enshroud answered 24/12, 2012 at 6:12 Comment(2)
@DWin I suggested an edit to add the decreasing argument to order to get the X largest/smallest elements in a row.Zweig
@NDThokare I don't think the edit went through, so I'll say it in a comment. To get the 2 largest elements, you add an element to order: t(apply(mat, 1, order, decreasing=TRUE)[ 1:2, ]).Zweig
M
0

What about

  • finding the indices of k largest values in each row

    apply(mat, 1, function(x, k) which(x <= max(sort(x, decreasing = F)[1:k]), arr.ind = T), k)`
    
  • finding the indices of k smallest values in each row

    apply(mat, 1, function(x, k) which(x >= min(sort(x, decreasing = T)[1:k]), arr.ind = T), k)`
    

On your example, for k <- 2, the former results in

     [,1] [,2] [,3] [,4] [,5]
[1,]    2    1    1    2    2
[2,]    4    3    2    3    3

and the latter results in

[[1]]
[1] 1 3 5

[[2]]
[1] 4 5

[[3]]
[1] 3 4

[[4]]
[1] 4 5

[[5]]
[1] 4 5

Change apply's second parameter from 1 to 2 for searching the columns.

Mercuri answered 3/12, 2015 at 9:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.