To calculate Minkowski distance in R, you can use the dist() function along with the method argument.

Minkowski distance is a generalized metric that includes Euclidean distance (p = 2) and Manhattan distance (p = 1) as special cases.

In this article, we will explore how to calculate Minkowski distance in R with examples.

Method: Use dist() Function

The dist() function in R is used to calculate distances between rows of a matrix. Here’s the syntax for calculating Minkowski distance:

dist(matrix, method = "minkowski", p)

The following example shows how to use the dist() function in R.

Use dist() Function to Calculate Minkowski Distance

Let’s see how we can calculate Minkowski distance between vectors using the dist() function:

# Declare vectors
x <- c(7, 8, 9, 4)
y <- c(5, 8, 9, 7)
z <- c(5, 7, 1, 2)

# Combine vectors into a matrix
matrix <- rbind(x, y, z)

# Calculate Minkowski distance with p = 3
minkowski_distance <- dist(matrix, method = "minkowski", p = 3)

# Display Minkowski distance
print(minkowski_distance)

Output: 👇️

         x        y
y 3.301927         
z 8.817296 8.503566

In this example, the dist() function calculates the Minkowski distance between the vectors x, y, and z with p = 3. The output shows the distances between each pair of vectors.