获取R中矩阵每行中K个最小或最大元素的索引

获取R中矩阵每行中K个最小或最大元素的索引,r,sorting,matrix,indices,R,Sorting,Matrix,Indices,如何求R中矩阵每行K个最小或最大元素的指数 例如,我有矩阵: 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 我想得到每一行中2个最小元素(以任何方式打破联系)的索引矩阵。结果应采用以下格式: 3 1 5 4 3 4 4 5 5 4 我尝试了一些使用sort、apply、arrayInd、which等的命令,但仍然无法得到想要的结果。 欢迎任何帮助 apply(mat,

如何求R中矩阵每行K个最小或最大元素的指数

例如,我有矩阵:

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
我想得到每一行中2个最小元素(以任何方式打破联系)的索引矩阵。结果应采用以下格式:

3 1
5 4
3 4
4 5
5 4
我尝试了一些使用
sort
apply
arrayInd
、which等的命令,但仍然无法得到想要的结果。 欢迎任何帮助

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
除了使用discreating=TRUE,您还可以将其用于一行中最大的两个:

t(apply(mat, 1, order)[ 5:4, ])    
那怎么办

  • 求每行k个最大值的指数

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

在您的示例中,对于
k@DWin,我建议进行编辑,将
discreating
参数添加到
order
中,以获得一行中的X个最大/最小元素。@NDThokare我认为编辑没有通过,因此我将在注释中说明。要获得最大的两个元素,您需要将一个元素添加到
order
t(apply(mat,1,order,discreating=TRUE)[1:2,])
     [,1] [,2] [,3] [,4] [,5]
[1,]    2    1    1    2    2
[2,]    4    3    2    3    3
[[1]]
[1] 1 3 5

[[2]]
[1] 4 5

[[3]]
[1] 3 4

[[4]]
[1] 4 5

[[5]]
[1] 4 5