*51*

TheÂ **Manhattan distance** between two vectors,Â *A* andÂ *B*,Â is calculated as:

Î£|a_{i} â€“ b_{i}|

where *i* is the i^{th} 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:

Î£|a_{i} â€“ b_{i}| = |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