To calculate euclidean distance in R, you can declare function manually.
The following method shows how you can do it with syntax.
Method: Declare Function
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 vector in R:
# Declare euclidean function
euclidean <- function(x1, x2) {
sqrt(sum((x1 - x2)^2))
}
# Declare vector
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
As the output shows euclidean distance between two vectors that we declare in above code.