简体   繁体   中英

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. I got stuck in a question about distance matrix. First I needed to calculate the distance matrix for the columns of the iris 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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