【问题标题】:R: how to find the indices of the maximal value per columnR:如何找到每列最大值的索引
【发布时间】: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]

非常感谢!

【问题讨论】:

    标签: r indexing


    【解决方案1】:

    使用 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
    

    或者另一个选项是colMaxs 和max.col

    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))
    

    【讨论】:

      【解决方案2】:

      转置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
      

      【讨论】:

        猜你喜欢
        • 2020-10-14
        • 1970-01-01
        • 2018-05-05
        • 2021-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-27
        • 1970-01-01
        相关资源
        最近更新 更多