Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get row and column number of cell that matches a given value in data.frame or distance matrix?

Tags:

dataframe

r

When I have a distance matrix (or a data frame based on a matrix), how do I get the row and column that corresponds to a given value?

Example:

df <- data.frame(x = c(11:20), y= c(12:21))
dst <- dist(df)

Output:

          1         2         3         4         5         6         7         8         9
2   1.414214                                                                                
3   2.828427  1.414214                                                                      
4   4.242641  2.828427  1.414214                                                            
5   5.656854  4.242641  2.828427  1.414214                                                  
6   7.071068  5.656854  4.242641  2.828427  1.414214                                        
7   8.485281  7.071068  5.656854  4.242641  2.828427  1.414214                              
8   9.899495  8.485281  7.071068  5.656854  4.242641  2.828427  1.414214                    
9  11.313708  9.899495  8.485281  7.071068  5.656854  4.242641  2.828427  1.414214          
10 12.727922 11.313708  9.899495  8.485281  7.071068  5.656854  4.242641  2.828427  1.414214

Now I want to input e.g. 11.313708 and get as output (9, 1)

like image 813
Azrael Avatar asked May 24 '16 09:05

Azrael


1 Answers

We convert to a matrix and get the index with which with arr.ind=TRUE (assuming that it is what you wanted).

 m1 <- as.matrix(dst)
 which(m1==val, arr.ind=TRUE)

Otherwise, we can use the regular subsetting by row, column if we already know the index of the value. As @nicola mentioned in the comments, there is a chance for floating point issues. To avoid that may be round it and then do the comparison. i.e.

 which(round(m1, 3)== 11.314, arr.ind=TRUE)
 #    row col
 #9    9   1
 #10  10   2
 #1    1   9
 #2    2  10
like image 121
akrun Avatar answered Sep 24 '22 11:09

akrun