2015-06-13 62 views
3

我想要均衡从原点到所有点的距离,其中点由具有两个坐标的数据帧给出。距离原点到空间中的点

我把所有的点为:

  x  y 
    1  0.0 0.0 
    2  -4.0 -2.8 
    3  -7.0 -6.5 
    4  -9.0 -11.1 
    5  -7.7 -16.9 
    6  -4.2 -22.4 
    7  -0.6 -27.7 
    8  3.0 -32.5 
    9  5.6 -36.7 
    10  8.4 -40.8 

为了让我的应用欧几里得距离向量的距离。我曾经尝试这样做:

distance <- function(trip) { 
    distance = lapply(trip, function (x) sqrt((trip[x,]-trip[1,])^2+ trip[,x]-trip[,1])^2)) 
    return(distance) 
} 

,这也:

distance = apply(trip,1, function (x) sqrt((trip[x,]-trip[1,])^2+ (trip[,x]-trip[,1])^2)) 
return(distance) 
+0

通过'DESIRED_DIST/DIST_FROM_ORIGIN'缩放点 – twentylemon

回答

6

有通过你的数据与apply功能各行无需循环。您可以计算在一杆与矢量运算全部在距离R:

(distance <- sqrt((trip$x - trip$x[1])^2 + (trip$y - trip$y[1])^2)) 
# [1] 0.000000 4.882622 9.552487 14.290206 18.571484 22.790349 27.706497 32.638168 37.124790 41.655732 

与矢量运算中计算所有的距离一下子就会快得多在你有很多点的情况。

1

没有为矩阵距离计算功能:

dist(trip, method = "euclidean") 

如果你不希望距离矩阵而只能从每个点到原点的距离,你可以子集的第一列as.matrix(dist(mat, method = "euclidean"))[1,]