Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distance between two 3D points in R

I have two 2 points A(x,y,z) e B(x1,y1,z1). I want to calculate the euclidean distance between these point at time1, time2, time3.

So, I have a matrix like this:

         x     y     z     x1     y1     z1    distance
time1    2     1     2      4      6      8       ?
time2    3     4     3      6      6      7       ?
time3    6     8     9      4      3      3       ?

As you can see above, I want to add a column (distance), in which I report the euclidean distance between A e B.

Have you any suggestions?

like image 856
piravi Avatar asked Dec 07 '25 04:12

piravi


1 Answers

You're looking for the dist() function:

df <- read.table(header = TRUE, text = "
         x     y     z     x1     y1     z1
time1    2     1     2      4      6      8
time2    3     4     3      6      6      7
time3    6     8     9      4      3      3")

df$distance <- apply(df, 1, function(x) dist(matrix(x, nrow = 2, byrow = TRUE)))

df
#>       x y z x1 y1 z1 distance
#> time1 2 1 2  4  6  8 8.062258
#> time2 3 4 3  6  6  7 5.385165
#> time3 6 8 9  4  3  3 8.062258

From help("dist"):

Description

This function computes and returns the distance matrix computed by using the specified distance measure to compute the distances between the rows of a data matrix.

Usage

dist(x, method = "euclidean", diag = FALSE, upper = FALSE, p = 2)

So, if you give it a m matrix like

2 1 2
4 6 8

distance(m) will calculate the euclidean distance between c(2, 1, 2) and c(4, 6, 8). Then we can just apply to each row of your dataset the dist() function called on a matrix constructed from that row, where the first row of the new matrix is the x, y, and z observations for that row of your dataset, and the second row of the new matrix is the x1, y1, and z1 observations for that row of your dataset.

like image 154
duckmayr Avatar answered Dec 08 '25 18:12

duckmayr