简体   繁体   English

如何计算 object(变量)和 R 中的组(两个变量)之间的距离矩阵

[英]How to calculate distance matrix between an object (variable) and a group (two variables) in R

First of all I am very new in R and I am trying to follow some tutorials.首先,我是 R 的新手,我正在尝试学习一些教程。 I got stuck in a question about distance matrix.我陷入了一个关于距离矩阵的问题。 First I needed to calculate the distance matrix for the columns of the iris dataframe.首先,我需要计算虹膜 dataframe 的列的距离矩阵。 I managed to do that.我设法做到了。

data(iris)
data<-iris
iris_t<-data.frame(t(iris[,-5]
colnames(iris_t<-rownamens(iris)
dist<-dist(iris_t)
dist        

However, now I have to consider the closest ones, Petal.Length and Sepal.Width , as a group and recalculate the distance matrix so that I get the distance between them.但是,现在我必须将最接近的Petal.LengthSepal.Width视为一个组并重新计算距离矩阵,以便获得它们之间的距离。 I have no idea how to do this.我不知道该怎么做。

If I get you correct:如果我让你正确:

D<-dist(t(iris[,-5]))
D = as.matrix(D)

You don't need to recalculate, just subset, the distances don't change:您不需要重新计算,只需子集,距离不会改变:

D[c("Petal.Length","Sepal.Width"),c("Petal.Length","Sepal.Width")]
             Petal.Length Sepal.Width
Petal.Length      0.00000    25.77809
Sepal.Width      25.77809     0.00000

If you want it as a distance object:如果你想要它作为一个距离 object:

as.dist(D[c("Petal.Length","Sepal.Width"),c("Petal.Length","Sepal.Width")])
            Petal.Length
Sepal.Width     25.77809

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM