Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

indexing

r

matrix

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 
like image 617
Tomas Avatar asked Sep 21 '11 23:09

Tomas


People also ask

Which function in Excel is used for matching INDEX?

=MATCH() returns the position of a cell in a row or column. Combined, the two formulas can look up and return the value of a cell in a table based on vertical and horizontal criteria. For short, this is referred to as just the Index Match function.

Is Xlookup better than INDEX match?

Let's recap how XLOOKUP outperforms VLOOKUP and INDEX/MATCH: It is the simplest function, with only 3 arguments needed in most cases because the default match_mode is 0 (exact match). It's a single function, unlike INDEX/MATCH, so it's faster to type.

Which function is used to find rows with matching criteria?

The MATCH() function is used to find at what row number the lookup value is found. Since we want to use the selected App in cell H22 and matching it with cells B22:B31 which contains the Apps, the function now becomes: Cell I22 = INDEX(C22:F31,MATCH(H22,B22:B31…


1 Answers

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 
like image 159
David Alber Avatar answered Sep 19 '22 14:09

David Alber