【发布时间】:2021-06-08 17:46:21
【问题描述】:
给定这个矩阵
mat
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 7 8 1
[3,] 4 5 6
我想找到所有列中的最大值加上它们的索引(行号)。所以基本上,我需要以下信息:
max = [7 8 6]
ind = [2 2 3]
非常感谢!
【问题讨论】:
给定这个矩阵
mat
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 7 8 1
[3,] 4 5 6
我想找到所有列中的最大值加上它们的索引(行号)。所以基本上,我需要以下信息:
max = [7 8 6]
ind = [2 2 3]
非常感谢!
【问题讨论】:
使用 apply 循环列 (MARGIN = 2),在名为 vector 的输出中获取 max 和最大值索引 (which.max)
apply(mat, 2, function(x) c(max = max(x), ind = which.max(x)))
-输出
[,1] [,2] [,3]
max 7 8 6
ind 2 2 3
library(matrixStats)
colMaxs(mat)
#[1] 7 8 6
max.col(t(mat))
#[1] 2 2 3
mat <- structure(c(1, 7, 4, 2, 8, 5, 3, 1, 6), .Dim = c(3L, 3L))
【讨论】:
转置mat并使用max.col
i = max.col(t(mat))
v = t(mat)[cbind(seq(NCOL(mat)), i)]
v
# [1] 7 8 6
i
# [1] 2 2 3
【讨论】: