*42*

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

(Σ|a_{i} – b_{i}|^{p})^{1/p}

where *i* is the i^{th} element in each vector and *p* is an integer.

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

To calculate the Minkowski distance between vectors in R, we can use the built-in **dist()** function with the following syntax:

**dist(x, method=”minkowski”, p)**

where:

**x:**A numeric matrix or data frame.**p:**The power to use in the Minkowski distance calculation.

Note that setting p = 1 is equivalent to calculating the Manhattan distance and setting p = 2 is equivalent to calculating the Euclidean distance.

This tutorial provides a couple examples of how to use this function in practice.

**Example 1: Minkowski Distance Between Two Vectors**

The following code shows how to use the **dist()** function to calculate the Minkowski distance between two vectors in R, using a power of p = 3:

#define two vectors a #bind the two vectors into a single matrix mat #calculate Minkowski distance between vectors using a power of 3 dist(mat, method="minkowski", p=3) a b 3.979057

The Minkowski distance (using a power of p = 3) between these two vectors turns out to be **3.979057**.

**Example 2: Minkowski Distance Between Vectors in a Matrix**

To calculate the Minkowski distance between several vectors in a matrix, we can use similar syntax in R:

#create four vectors a #bind vectors into one matrix mat #calculate Minkowski distance between vectors using a power of 3 dist(mat, method = "minkowski", p=3) a b c b 3.979057 c 8.439010 5.142563 d 3.332222 6.542133 10.614765

The way to interpret this output is as follows:

- The Minkowski distance between vector
*a*and*b*is**3.98**. - The Minkowski distance between vector
*a*and*c*is**8.43**. - The Minkowski distance between vector
*a*and*d*is**3.33**. - The Minkowski distance between vector
*b*and*c*is**5.14**. - The Minkowski distance between vector
*b*and*d*is**6.54**. - The Minkowski distance between vector
*c*and*d*is**10.61**.

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

**Additional Resources**

How to Calculate Euclidean Distance in R

How to Calculate Hamming Distance in R

How to Calculate Manhattan Distance in R

How to Calculate Mahalanobis Distance in R