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.
D. kaufmann
source share