Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract diagonals from a distance matrix in R

I would like to know how can I extract the values of the first diagonal from a distance matrix.

For example:

> mymatrix
     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    6    4
[4,]    8    6

> dist(mymatrix)

         1        2        3
2 2.828427                  
3 5.385165 3.000000         
4 8.062258 5.385165 2.828427

I want to get in a vector the values: 2.828427, 3.000000, 2.828427

Thanks!

like image 207
pateto777 Avatar asked Nov 01 '25 01:11

pateto777


1 Answers

One work around is to convert the dist object to matrix and then extract elements where row index is one larger than the column index:

mat = as.matrix(dist(mymatrix))
mat[row(mat) == col(mat) + 1]
# [1] 2.828427 3.000000 2.828427
like image 65
Psidom Avatar answered Nov 03 '25 05:11

Psidom