`which()`用于矩阵索引的函数

TMS*_*TMS 31 indexing r matrix

假设我有一些矩阵,例如:

> m = matrix(rep(c(0, 0, 1), 4), nrow = 4)
> m
     [,1] [,2] [,3]
[1,]    0    0    1
[2,]    0    1    0
[3,]    1    0    0
[4,]    0    0    1
Run Code Online (Sandbox Code Playgroud)

如果我跑which,我得到正常指数列表:

> which(m == 1)
[1]  3  6  9 12
Run Code Online (Sandbox Code Playgroud)

我希望得到像矩阵索引这样的东西 - 每个索引都包含行号和列号:

     [,1] [,2]
[1,]    3    1
[2,]    2    2
[3,]    1    3
[4,]    4    3
Run Code Online (Sandbox Code Playgroud)

这有什么简单的功能吗?此外,它应该以某种方式包含行和列名称:

> rownames(m) = letters[1:4]
> colnames(m) = letters[5:7]
> m
  e f g
a 0 0 1
b 0 1 0
c 1 0 0
d 0 0 1
Run Code Online (Sandbox Code Playgroud)

但我现在不怎么样,也许就像

     [,1] [,2] [,3] [,4]
[1,]    3    1    c    e
[2,]    2    2    b    f
[3,]    1    3    a    g
[4,]    4    3    d    g
Run Code Online (Sandbox Code Playgroud)

或者,可能返回2个向量(用于行和列),例如

c b a d
3 2 1 4

e f g g
1 2 3 3
Run Code Online (Sandbox Code Playgroud)

Dav*_*ber 52

对于您的第一个问题,您还需要传递arr.ind= TRUEwhich:

> which(m == 1, arr.ind = TRUE)
     row col
[1,]   3   1
[2,]   2   2
[3,]   1   3
[4,]   4   3
Run Code Online (Sandbox Code Playgroud)


42-*_*42- 6

你不能在矩阵中混合数字和alpha,但你可以在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
Run Code Online (Sandbox Code Playgroud)