从R中的距离矩阵中提取对角线 [英] Extract diagonals from a distance matrix in R

查看:1245
本文介绍了从R中的距离矩阵中提取对角线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何从距离矩阵中提取第一个对角线的值.

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

例如:

> 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

我想获取向量值:2.828427, 3.000000, 2.828427

谢谢!

推荐答案

一种解决方法是将dist对象转换为matrix,然后提取行索引比列索引大一个的元素:

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

这篇关于从R中的距离矩阵中提取对角线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆