【问题标题】:Locating which elements of a matrix are outputted定位输出矩阵的哪些元素
【发布时间】:2018-08-14 11:18:37
【问题描述】:

如果我有一个 100 x 100 矩阵,我想找到最高的 20 个值,并且我成功地使用了:

mat <- matrix(data = rexp(200, rate = 10), nrow = 100, ncol = 100)
tail(sort(mat), 20)

#[1] 0.6599044 0.6599044 0.6599044 0.6599044 0.6599044 0.6601134 0.6601134 0.6601134 0.6601134 0.6601134
#[11] 0.6669251 0.6669251 0.6669251 0.6669251 0.6669251 1.0284198 1.0284198 1.0284198 1.0284198 1.0284198

但是现在我该如何输出它们在矩阵中的位置呢?

【问题讨论】:

    标签: r matrix output tail


    【解决方案1】:

    我们可以使用orderarrayInd函数。

    mat <- matrix(data = rexp(200, rate = 10), nrow = 100, ncol = 100)
    arrayInd(order(mat, decreasing = TRUE)[1:20], .dim = dim(mat))
    

    一个小例子

    set.seed(0)
    mat <- round(matrix(data = rexp(25, rate = 10), nrow = 5, ncol = 5), 4)
    #       [,1]   [,2]   [,3]   [,4]   [,5]
    #[1,] 0.0184 0.1230 0.0762 0.1876 0.0642
    #[2,] 0.0146 0.0540 0.1238 0.0655 0.0294
    #[3,] 0.0140 0.0957 0.4424 0.0337 0.0566
    #[4,] 0.0436 0.0147 0.1055 0.0588 0.0106
    #[5,] 0.2895 0.1391 0.1035 0.2365 0.0059
    
    ## 1D index of the first 4 largest values
    ind1D <- order(mat, decreasing = TRUE)[1:4]
    # [1] 13  5 20 16
    
    ## 2D index
    ind2D <- arrayInd(ind1D, .dim = dim(mat))
    #     [,1] [,2]
    #[1,]    3    3
    #[2,]    5    1
    #[3,]    5    4
    #[4,]    1    4
    
    ## inspect corresponding matrix elements, using either 1D or 2D index
    mat[ind1D]
    #[1] 0.4424 0.2895 0.2365 0.1876
    
    mat[ind2D]
    #[1] 0.4424 0.2895 0.2365 0.1876
    

    arrayInd 中还有一个 .dimanmes 参数,您可以设置它。 arrayIndwhich(, arr.ind = TRUE) 的主力。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多