获取矩阵的最小元素的行和列名称

Seb*_*ian 36 r matrix

我需要获取矩阵中最小元素的行和列名称

> mat = matrix(data=runif(12), nrow = 4, ncol=4)
> rownames(mat) = colnames(mat) = letters[1:4]
> 
> mat
  a         b         c         d
a 0.3167865 0.6958895 0.4233572 0.3167865
b 0.1042599 0.1552235 0.8461520 0.1552235
c 0.6286461 0.9749868 0.2390978 0.6286461
d 0.5923721 0.7823673 0.8427426 0.5923721
> min = min(mat)
> min
> 0.1042599
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我想得到"a"和"b"

bna*_*aul 42

> inds = which(mat == min(mat), arr.ind=TRUE)
> inds
  row col
a   1   2
> rnames = rownames(mat)[inds[,1]]
> cnames = colnames(mat)[inds[,2]]
Run Code Online (Sandbox Code Playgroud)

This will give you the row/column names for each entry that equals the minimum value; if you just want the first one, you could only check inds[1,1] and inds[1,2].

  • 你也可以做`inds < - arrayInd(which.min(mat),dim(mat))`.这样可以省去分配`==`的结果并保证单行. (20认同)