How do I find the Euclidean distance of two vectors:
x1 <- rnorm(30) x2 <- rnorm(30)
Formula to calculate this distance is : Euclidean distance = √Σ(xi-yi)^2 where, x and y are the input values. The distance between 2 arrays can also be calculated in R, the array function takes a vector and array dimension as inputs.
Euclidean Distance Examples Determine the Euclidean distance between two points (a, b) and (-a, -b). d = 2√(a2+b2). Hence, the distance between two points (a, b) and (-a, -b) is 2√(a2+b2).
In mathematics, the Euclidean distance between two points in Euclidean space is the length of a line segment between the two points. It can be calculated from the Cartesian coordinates of the points using the Pythagorean theorem, therefore occasionally being called the Pythagorean distance.
Use the dist()
function, but you need to form a matrix from the two inputs for the first argument to dist()
:
dist(rbind(x1, x2))
For the input in the OP's question we get:
> dist(rbind(x1, x2)) x1 x2 7.94821
a single value that is the Euclidean distance between x1
and x2
.
As defined on Wikipedia, this should do it.
euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))
There's also the rdist
function in the fields
package that may be useful. See here.
EDIT: Changed **
operator to ^
. Thanks, Gavin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With