计算存储在数据框中的配置文件之间的欧氏距离。使用一行作为参考

时间:2016-07-20 09:35:46

标签: r

我有一个类似下面的数据框:

> dput(data)
structure(list(`28` = c(0, 0, 0, 0, 0, 0), `38` = c(0, 0, 0, 
0, 0, 0), `45` = c(0, 0, 0, 0, 0, 0), `53` = c(0, 0, 0, 0, 0, 
0), `60` = c(0, 0, 0, 0, 0, 0), `78` = c(0, 0, 0, 0, 0, 0), `116` = c(0, 
0, 0, 0, 0, 0.983309489747258), `145` = c(0, 0, 0, 0, 0, 1), 
    `189` = c(0, 1, 0.560384508734634, 0, 0, 0.875695437927198
    ), `223` = c(0, 0.988158197286733, 1, 0, 0, 0.492500108379937
    ), `281` = c(1, 0.677856978615774, 0.448525741750624, 0, 
    0.362088745790311, 0.180474270603026), `362` = c(0.79151704397606, 
    0.763278914693033, 0.35864682503004, 1, 1, 0.114178985852806
    ), `440` = c(0.662841530054645, 0.818636468153598, 0.448488769756909, 
    0, 0.448447503793346, 0), `524` = c(0, 0.638192687974247, 
    0, 0, 0, 0), `634` = c(0, 0, 0, 0, 0, 0), `759` = c(0, 0, 
    0, 0, 0, 0), `848` = c(0, 0, 0, 0, 0, 0), `979` = c(0, 0, 
    0, 0, 0, 0), `1120` = c(0, 0, 0, 0, 0, 0), `1248` = c(0, 
    0, 0, 0, 0, 0)), .Names = c("28", "38", "45", "53", "60", 
"78", "116", "145", "189", "223", "281", "362", "440", "524", 
"634", "759", "848", "979", "1120", "1248"), row.names = c("Mark", 
"Gregg", "Tim", "Oscar", "Tom", "Matthew"
), class = "data.frame")

我想根据这些数据计算所有配置文件之间的欧氏距离,Tim应该用作参考。结果可以存储在附加列中。

Mark to Tim

Gregg to Tim

奥斯卡到蒂姆

1 个答案:

答案 0 :(得分:3)

您可以使用dist功能(实际上计算所有配置文件之间的所有距离):

m <- as.matrix(DF)
distances <- as.matrix(dist(m, method = "euclidean", upper = TRUE,diag = TRUE))

> distances['Mark','Tim']
[1] 1.36069

> distances['Gregg','Tim']
[1] 0.9767401

> distances['Oscar','Tim']
[1] 1.458658