may*_*cca 7 r matrix euclidean-distance
我在欧氏距离计算中非常迷失.我发现函数dist2 {SpatialTools}或rdist {fields}来执行此操作,但它们不能按预期工作.
我想一个点在carthesian系统中有两个坐标,所以[x,y].要测量2个点之间的距离(由行定义),我需要2个点的4个坐标,所以点A:[x1,y1]点B:[x2,y2]
积分协调:
A[0,1]
B[0,0]
C[1,1]
D[1,1]
Run Code Online (Sandbox Code Playgroud)
我有两个矩阵:x1(A和C在那里,由行定义)和x2(包含B和D).写在矩阵中:
library("SpatialTools")
x1<-matrix(c(0,1,1,1), nrow = 2, ncol=2, byrow=TRUE)
x2<-matrix(c(0,0,1,1), nrow = 2, ncol=2, byrow=TRUE)
Run Code Online (Sandbox Code Playgroud)
所以我得到了
> x1
[,1] [,2]
[1,] 0 1 #(as xy coordinates of A point)
[2,] 1 1 #(same for C point)
> x2
[,1] [,2]
[1,] 0 0 #(same for B point)
[2,] 1 1 #(same for D point)
Run Code Online (Sandbox Code Playgroud)
计算之间的欧氏距离
A <-> B # same as x1[1,] <-> x2[1,]
C <-> D # same as x1[2,] <-> x2[2,]
Run Code Online (Sandbox Code Playgroud)
我假设获得EuclidDist:
> x1 x2 EuclidDist
[,1] [,2] [,1] [,2]
[1,] 0 1 #A [1,] 0 0 #B 1
[2,] 1 1 #B [2,] 1 1 #D 0
Run Code Online (Sandbox Code Playgroud)
我想获得由[x,y]坐标识别的两点之间的距离矢量,但是,使用dist2
我得到一个矩阵:
> dist2(x1,x2)
[,1] [,2]
[1,] 1.000000 1
[2,] 1.414214 0
Run Code Online (Sandbox Code Playgroud)
我的问题是,哪些数字描述了这个矩阵中AB和CD之间真正的欧几里德距离?我误会了什么吗?非常感谢你的每一条建议或任何解释.
Sha*_*bho 13
如果你只想要一个矢量,这样的东西对你有用.
尝试这样的事情:
euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))
library(foreach)
foreach(i = 1:nrow(x1), .combine = c ) %do% euc.dist(x1[i,],x2[i,])
Run Code Online (Sandbox Code Playgroud)
这适用于任何尺寸.
如果您不想使用foreach,可以使用简单的循环:
dist <- NULL
for(i in 1:nrow(x1)) dist[i] <- euc.dist(x1[i,],x2[i,])
dist
Run Code Online (Sandbox Code Playgroud)
虽然,我会推荐foreach(因为这对于像这样的各种任务很容易).在包的文档中阅读更多相关信息.