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!
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