`which()` function for matrix indices

后端 未结 2 717
滥情空心
滥情空心 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
    

提交回复
热议问题