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

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

eg. I have a 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 would like to get an index matrix of the 2 smallest elements (in any case, breaking ties) in each row. The result should be in the following format:

 3 1 5 4 3 4 4 5 5 4 

I tried several commands with sort , apply , arrayInd , which , etc. But still could not get the desired result. Any help is appreciated.

+8
sorting matrix r
source share
2 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 decrease = TRUE, you could also use this for the two largest lines:

 t(apply(mat, 1, order)[ 5:4, ]) 
+11
source share

What about

  • finding the indices of k highest 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 least values ​​in each row

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

In your example, for k <- 2 , the first result in

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

and the latter leads to

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

Change the apply second parameter from 1 to 2 to search for columns.

0
source share

All Articles