N D*_*are 8 sorting r matrix indices
如何在R的矩阵的eaach行中得到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
Run Code Online (Sandbox Code Playgroud)
我想在每行中获得指数2个最小元素(以任何方式打破关系)的指数矩阵.结果应采用以下格式:
3 1
5 4
3 4
4 5
5 4
Run Code Online (Sandbox Code Playgroud)
我试着用一些命令sort,apply,arrayInd,which等,但仍无法获得期望的结果.欢迎任何帮助.
42-*_*42- 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
Run Code Online (Sandbox Code Playgroud)
除了使用decrease = TRUE之外,你还可以将它用于连续两个最大值:
t(apply(mat, 1, order)[ 5:4, ])
Run Code Online (Sandbox Code Playgroud)