10.9 C
London
Friday, May 9, 2025
HomeRDescriptive Statistics in RHow to Calculate Euclidean Distance in R (With Examples)

How to Calculate Euclidean Distance in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

The Euclidean distance between two vectors, A and B, is calculated as:

Euclidean distance = √Σ(Ai-Bi)2

To calculate the Euclidean distance between two vectors in R, we can define the following function:

euclidean function(a, b) sqrt(sum((a - b)^2))

We can then use this function to find the Euclidean distance between any two vectors:

#define two vectors
a #calculate Euclidean distance between vectors
euclidean(a, b)

[1] 12.40967

The Euclidean distance between the two vectors turns out to be 12.40967.

Note that we can also use this function to calculate the Euclidean distance between two columns of a data frame:

#define data frame
df #calculate Euclidean distance between columns a and d
euclidean(df$a, df$d)

[1] 7.937254

Note that this function will produce a warning message if the two vectors are not of equal length:

#define two vectors of unequal length
a #attempt to calculate Euclidean distance between vectors
euclidean(a, b)

[1] 23.93742
Warning message:
In a - b : longer object length is not a multiple of shorter object length

You can refer to this Wikipedia page to learn more details about Euclidean distance.

Additional Resources

How to Calculate Manhattan Distance in R
How to Calculate Minkowski Distance in R
How to Calculate Hamming Distance in R
How to Calculate Mahalanobis Distance in R
How to Calculate Levenshtein Distance in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories