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

How to Calculate Manhattan 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 Manhattan distance between two vectors, A and B, is calculated as:

Σ|ai – bi|

where i is the ith element in each vector.

This distance is used to measure the dissimilarity between any two vectors and is commonly used in many different machine learning algorithms.

This tutorial provides a couple examples of how to calculate Manhattan distance in R.

Example 1: Manhattan Distance Between Two Vectors

The following code shows how to create a custom function to calculate the Manhattan distance between two vectors in R:

#create function to calculate Manhattan distance
manhattan_dist function(a, b){
     dist abs(a-b)
     dist sum(dist)
     return(dist)
}

#define two vectors
a #calculate Manhattan distance between vectors
manhattan_dist(a, b)

[1] 9

The Manhattan distance between these two vectors turns out to be 9.

We can confirm this is correct by quickly calculating the Manhattan distance by hand:

Σ|ai – bi| = |2-5| + |4-5| + |4-7| + |6-8| = 3 + 1 + 3 + 2 = 9.

Example 2: Manhattan Distance Between Vectors in a Matrix

To calculate the Manhattan distance between several vectors in a matrix, we can use the built-in dist() function in R:

#create four vectors
a #bind vectors into one matrix
mat #calculate Manhattan distance between each vector in the matrix
dist(mat, method = "manhattan")

   a  b  c
b  9      
c 19 10   
d  7 16 26

The way to interpret this output is as follows:

  • The Manhattan distance between vector a and b is 9.
  • The Manhattan distance between vector a and c is 19.
  • The Manhattan distance between vector a and d is 7.
  • The Manhattan distance between vector b and c is 10.
  • The Manhattan distance between vector b and d is 16.
  • The Manhattan distance between vector c and d is 26.

Note that each vector in the matrix should be the same length.

Additional Resources

How to Calculate Euclidean Distance in R
How to Calculate Mahalanobis Distance in R
How to Calculate Minkowski 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