Alexis Begni
Alexis Begni

Reputation: 106

How to get distance between points and multiple others

I'm trying to determine the distances (euclidean) between points I have in a data frame and others in another one. Here's below an example of data.

x <- rnorm(5)
y <- rnorm(5)
df <- data.frame(x, y)

x1 <- rnorm(5)
y1 <- rnorm(5)
Id <- c(1:5)
df2 <- data.frame(Id, x1, y1)

I tried this formula to get distance:

sqrt(((df2$x1 - df$x)^2) + ((df2$y1 - df$y)^2))

But I cannot find how to get the distance between points by Id in the df1 and all the others in df

thanks for the help

Upvotes: 0

Views: 80

Answers (1)

Ben
Ben

Reputation: 30474

If you wanted to get distances between each (x,y) point in df2 with all of the other (x,y) points in df, you could do the following, using your Euclidean distance formula:

euclid_dist <- function(x1, y1, x2, y2) {
  sqrt(((x1 - x2)^2) + ((y1 - y2)^2))
}

t(apply(df2, 1, function(a) euclid_dist(a[["x1"]], a[["y1"]], df[["x"]], df[["y"]])))

With your data you would get in return:

set.seed(123)

x <- rnorm(5)
y <- rnorm(5)
df <- data.frame(x, y)

x1 <- rnorm(5)
y1 <- rnorm(5)
Id <- c(1:5)
df2 <- data.frame(Id, x1, y1)

         [,1]      [,2]     [,3]      [,4]      [,5]
[1,] 1.786003 1.9680289 3.070264 2.7295146 2.4865570
[2,] 1.525957 0.5911463 2.131949 1.2195161 0.9712662
[3,] 3.805099 2.5081895 1.353883 1.3216922 1.5449945
[4,] 1.215755 0.4171294 2.442043 1.3887899 1.1471688
[5,] 2.187861 0.9888714 2.258099 0.6619184 0.6856658

This matrix includes distances where each row represents each Id in df2.

Upvotes: 1

Related Questions