`which()` function for matrix indices

后端 未结 2 714
滥情空心
滥情空心 2020-12-09 07:51

Say I have some matrix, for example:

> m = matrix(rep(c(0, 0, 1), 4), nrow = 4)
> m
     [,1] [,2] [,3]
[1,]    0    0    1
[2,]    0    1    0
[3,]            


        
相关标签:
2条回答
  • 2020-12-09 08:18

    You cannot mix numeric and alpha in a matrix, but you can in a data.frame:

    > indices <- data.frame(ind= which(m == 1, arr.ind=TRUE))
    > indices$rnm <- rownames(m)[indices$ind.row]
    > indices$cnm <- colnames(m)[indices$ind.col]
    > indices
      ind.row ind.col rnm cnm
    c       3       1   c   e
    b       2       2   b   f
    a       1       3   a   g
    d       4       3   d   g
    
    0 讨论(0)
  • 2020-12-09 08:19

    For your first question you need to also pass arr.ind= TRUE to which:

    > which(m == 1, arr.ind = TRUE)
         row col
    [1,]   3   1
    [2,]   2   2
    [3,]   1   3
    [4,]   4   3
    
    0 讨论(0)
提交回复
热议问题