Find the largest values on a matrix in R

社会主义新天地 提交于 2021-02-10 03:11:46

问题


I am working on a matrix in R, 230 x 230 and I want to extract the 10 (or any other number than 1) max inputs on the matrix, both their position and value.

The extra problem is that this is a similarity matrix, so I have 1s in the diagonal which of course I want to leave out of the max search.

Any ideas or commands for that?


回答1:


A neat way to do this in general is with the underused arrayInd function, which gives you row and column positions for plain jane vector positions. That's how which(..., arr.ind = TRUE) does it. Here's how you might do it:

## creating a random 230x230 matrix
n <- 230;
set.seed(1);
m <- matrix(sample.int(100000, n*n, replace = TRUE), n, n);
diag(m) <- 1;

## function to return n largest values and position for matrix m
nlargest <- function(m, n, sim = TRUE) {
  mult <- 1;
  if (sim) mult <- 2;
  res <- order(m)[seq_len(n) * mult];
  pos <- arrayInd(res, dim(m), useNames = TRUE);
  list(values = m[res],
       position = pos)
}

diag(m) <- NA;
nlargest(m, 10);
# $values
# [1]  1  2 11 12 12 12 13 18 21 22
#
# $position
#      row col
# [1,]  59  95
# [2,] 178 202
# [3,] 160  34
# [4,]  83 151
# [5,] 150 194
# [6,]  18 225
# [7,]  13  38
# [8,] 206 182
# [9,]  89  22
#[10,] 142  99


来源:https://stackoverflow.com/questions/32544566/find-the-largest-values-on-a-matrix-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!