【问题标题】:how to calculate Euclidean distance between all rows of a data frame and the last row in r如何计算数据框的所有行与r中的最后一行之间的欧几里得距离
【发布时间】:2019-10-01 01:40:59
【问题描述】:

我有一个数据框,想计算所有行与最后一行之间的欧几里得距离,并使用距离函数将距离值作为新列添加到数据框。

你知道我该怎么做吗?

这是一个数据框的例子:

df = data.frame(
      x = rnorm(10),
      y = rnorm(10),
      z = rnorm(10)
 )

这是想要的输出

        x          y           z     dist
1   2.4720136 -2.5332449 -0.29877255 1.956157
2   0.2616905 -0.5988683 -0.68586911 3.434874
3   0.4706199 -0.7911288 -0.07673025 2.700038
4   0.7202775 -2.0615370 -0.93959256 2.493054
5  -0.3002038  1.5872991  1.43678171 2.310108
6  -2.1274192  1.9746993  0.55372197 4.39925
7   0.2568586  0.2206467  0.22742260 3.482363
8   1.3476458 -0.2029571 -0.98492886 1.459337
9  -1.1968263 -0.4381387  0.93461394 2.180699
10 -0.2995206 -1.6586264 -0.25067014 NA

【问题讨论】:

  • 您能否添加一个可重现的示例以及预期的输出?
  • as.matrix(pdist::pdist(dt[nrow(dt),], dt[-nrow(dt),]))
  • apply(df, 1, function(xx) {sqrt(sum((xx - df[nrow(df),])^2))}) 这将给出所有距离,然后您可以将其添加到 df 并在末尾连接 0

标签: r dataframe vector distance euclidean-distance


【解决方案1】:

您可以使用dist 查找数据框每一行之间的距离,例如:

df = data.frame(
    x = rnorm(10),
    y = rnorm(10),
    z = rnorm(10)
)

# This will generate all the pairwise differences
#   Might be an issue of very large datasets
#   where speed will be an issue
df$dist = as.matrix(dist(df))[nrow(df), ]

【讨论】:

  • 感谢您的回复。但我想知道所有行之间的距离,只有最后一行。 (row1, row10), (row2, row10), (row3, row10) , ...
  • 这应该是我的代码所做的,它生成成对距离,但只保存到最后一行的距离。你看到了什么不同的东西吗?
猜你喜欢
  • 2020-06-19
  • 2020-01-23
  • 1970-01-01
  • 2017-09-08
  • 2016-02-06
  • 2014-04-09
  • 2013-08-22
  • 2021-01-23
相关资源
最近更新 更多