我希望找到矩阵的最大元素值及其位置(在矩阵的行ID和列ID中)。
我正在使用以下函数返回矩阵的行和列。
这似乎是一个糟糕的技巧-这是我可能缺少本机方法的一种情况。有更好的/更多的R方法吗?
这是我的功能:
matxMax <- function(mtx)
{
colmn <- which(mtx == max(mtx)) %/% nrow(mtx) + 1
row <- which(mtx == max(mtx)) %% nrow(mtx)
return( matrix(c(row, colmn), 1))
}
我使用如下:
mm <- matrix(rnorm(100), 10, 10)
maxCords <- matxMax(mm)
mm[maxCords]
你可以做
## Some data
set.seed(123)
mm <- matrix(rbinom(40, 20, 0.5), 8, 5)
mm
# [,1] [,2] [,3] [,4] [,5]
# [1,] 9 10 8 11 11
# [2,] 12 10 6 11 12
# [3,] 9 14 9 10 6
# [4,] 13 10 14 11 10
# [5,] 13 11 13 9 12
# [6,] 6 10 11 8 8
# [7,] 10 7 11 14 9
# [8,] 13 13 16 13 8
which(mm == max(mm), arr.ind = TRUE)
# row col
# [1,] 8 3
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句