# How to Calculate Manhattan Distance in R (With Examples)

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 <- c(2, 4, 4, 6)

b <- c(5, 5, 7, 8)

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

 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 <- c(2, 4, 4, 6)

b <- c(5, 5, 7, 8)

c <- c(9, 9, 9, 8)

d <- c(1, 2, 3, 3)

#bind vectors into one matrix
mat <- rbind(a, b, c, d)

#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.