Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

r - Get row and column indices of matches using `which()`

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,]    1    0    0
[4,]    0    0    1

If I run which, I get list of normal indices:

> which(m == 1)
[1]  3  6  9 12

I want to get something like matrix indices - each index containing the row and column number:

     [,1] [,2]
[1,]    3    1
[2,]    2    2
[3,]    1    3
[4,]    4    3

Is there any simple function to do this? Moreover, it should somehow contain the row and column names:

> 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

but I don't now how, maybe like

     [,1] [,2] [,3] [,4]
[1,]    3    1    c    e
[2,]    2    2    b    f
[3,]    1    3    a    g
[4,]    4    3    d    g

or, maybe return 2 vectors (for rows and columns), like

c b a d
3 2 1 4

e f g g
1 2 3 3
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...