求矩阵R中每一行K个最小或最大元素的指标

时间:2022-02-06 13:38:23

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

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

E.g. I have matrix:

如我有矩阵:

2   3   1  65  246  7   9  3   29   45  3  5   724  65  87 3   634  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 15 43 44 55 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


11  

apply(mat, 1, which.max)  #.....largestapply(mat, 1, which.min)  #.....smallestt(apply(mat, 1, sort)[ 1:2, ])  # 2 smallest in each rowt(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:

除了使用递减=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.

将apply的第二个参数从1更改为2以搜索列。

#1


11  

apply(mat, 1, which.max)  #.....largestapply(mat, 1, which.min)  #.....smallestt(apply(mat, 1, sort)[ 1:2, ])  # 2 smallest in each rowt(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:

除了使用递减=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.

将apply的第二个参数从1更改为2以搜索列。