To calculate Euclidean distance in R, you can declare a function manually. Euclidean distance is a measure of the true straight line distance between two points in Euclidean space.
In this article, we will explore how to calculate Euclidean distance in R with examples.
Method: Declare Function
You can declare a function to calculate Euclidean distance between two vectors. Here’s the syntax:
euclidean <- function(x1, x2) {
sqrt(sum((x1 - x2)^2))
}
The following example shows how to calculate Euclidean distance in R.
Calculate Euclidean Distance
Let’s see how to calculate Euclidean distance between two vectors in R:
# Declare euclidean function
euclidean <- function(x1, x2) {
sqrt(sum((x1 - x2)^2))
}
# Declare vectors
a <- c(78, 85, 89, 96, 74, 75)
b <- c(65, 66, 64, 69, 70, 61)
# Calculate Euclidean distance
d <- euclidean(a, b)
# Show Euclidean distance
print(d)
Output: 👇️
[1] 45.78209
In this example, the euclidean
function calculates the Euclidean distance between vectors a
and b
. The output shows the distance between the two vectors.