Distance to a point in space
I want to align the distance from the origin to all points where the points are given by a 2-coordinate dataframe.
I have all points like:
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
To get the distance, I am applying Euclidean distance to the vector. I've tried this:
distance <- function(trip) {
distance = lapply(trip, function (x) sqrt( (trip[x,]-trip[1,] )^2+ trip[,x]-trip[,1] )^2))
return(distance)
}
and this also:
distance = apply(trip,1, function (x) sqrt( (trip[x,]-trip[1,] )^2+ (trip[,x]-trip[,1] )^2))
return(distance)
+3
source to share
2 answers
There is no need to iterate over individual lines of your data with a function apply
. You can calculate all distances in one shot using vectorized arithmetic in 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
Calculating all distances at once using vectorized operations will be much faster in cases where you have many points.
+6
source to share