gpt4 book ai didi

r - 来自两个独立数据帧的距离矩阵

转载 作者:行者123 更新时间:2023-12-04 09:16:29 26 4
gpt4 key购买 nike

我想创建一个矩阵,其中包含来自一个数据帧的行与来​​自另一个数据帧的行的欧几里德距离。例如,假设我有以下数据框:

a <- c(1,2,3,4,5)
b <- c(5,4,3,2,1)
c <- c(5,4,1,2,3)
df1 <- data.frame(a,b,c)

a2 <- c(2,7,1,2,3)
b2 <- c(7,6,5,4,3)
c2 <- c(1,2,3,4,5)
df2 <- data.frame(a2,b2,c2)

我想创建一个矩阵,其中包含 df1 中每一行与 df2 行的距离。

所以 matrix[2,1] 应该是 df1[2,] 和 df2[1,] 之间的欧几里德距离。 matrix[3,2] df[3,] 和 df2[2,] 之间的距离等。

有谁知道这是如何实现的?

最佳答案

也许您可以使用 fields 包:函数 rdist 可能会执行您想要的操作:

rdist : Euclidean distance matrix
Description: Given two sets of locations computes the Euclidean distance matrix among all pairings.


> rdist(df1, df2)
[,1] [,2] [,3] [,4] [,5]
[1,] 4.582576 6.782330 2.000000 1.732051 2.828427
[2,] 4.242641 5.744563 1.732051 0.000000 1.732051
[3,] 4.123106 5.099020 3.464102 3.316625 4.000000
[4,] 5.477226 5.000000 4.358899 3.464102 3.316625
[5,] 7.000000 5.477226 5.656854 4.358899 3.464102
pdist 包的情况类似

pdist : Distances between Observations for a Partitioned Matrix
Description: Computes the euclidean distance between rows of a matrix X and rows of another matrix Y.


> pdist(df1, df2)
An object of class "pdist"
Slot "dist":
[1] 4.582576 6.782330 2.000000 1.732051 2.828427 4.242640 5.744563 1.732051
[9] 0.000000 1.732051 4.123106 5.099020 3.464102 3.316625 4.000000 5.477226
[17] 5.000000 4.358899 3.464102 3.316625 7.000000 5.477226 5.656854 4.358899
[25] 3.464102
attr(,"Csingle")
[1] TRUE

Slot "n":
[1] 5

Slot "p":
[1] 5

Slot ".S3Class":
[1] "pdist"

#

注意:如果您正在寻找行之间的欧几里得范数,您可能想尝试:
a <- c(1,2,3,4,5)
b <- c(5,4,3,2,1)
c <- c(5,4,1,2,3)
df1 <- rbind(a, b, c)

a2 <- c(2,7,1,2,3)
b2 <- c(7,6,5,4,3)
c2 <- c(1,2,3,4,5)
df2 <- rbind(a2,b2,c2)

rdist(df1, df2)

这给出:
> rdist(df1, df2)
[,1] [,2] [,3]
[1,] 6.164414 7.745967 0.000000
[2,] 5.099020 4.472136 6.324555
[3,] 4.242641 5.291503 5.656854

关于r - 来自两个独立数据帧的距离矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39560993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com