Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 790
N D Thokare Avatar asked Dec 24 '12 06:12

N D Thokare


1 Answers

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, ])    
like image 125
IRTFM Avatar answered Oct 18 '22 21:10

IRTFM