How to get indices of K smallest or largest elements in eaach row of a matrix in R?
如何在R的矩阵的eaach行中得到K个最小或最大元素的索引?
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:
我想在每一行中获得指数2个最小元素(以任何方式打破关系)的指数矩阵。结果应采用以下格式:
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.
我尝试使用sort,apply,arrayInd等几个命令,但仍然无法获得所需的结果。欢迎任何帮助。
2 个解决方案
#1
12
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:
除了使用decrease = TRUE之外,您还可以将它用于连续两个最大值:
t(apply(mat, 1, order)[ 5:4, ])
#2
0
What about
-
finding the indices of k largest values in each row
找到每行中k个最大值的索引
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
找到每行中k个最小值的索引
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
在你的例子中,对于k < - 2,前者导致
[,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.
将应用的第二个参数从1更改为2以搜索列。
#1
12
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:
除了使用decrease = TRUE之外,您还可以将它用于连续两个最大值:
t(apply(mat, 1, order)[ 5:4, ])
#2
0
What about
-
finding the indices of k largest values in each row
找到每行中k个最大值的索引
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
找到每行中k个最小值的索引
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
在你的例子中,对于k < - 2,前者导致
[,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.
将应用的第二个参数从1更改为2以搜索列。