Method 1:Using a custom function
We can calculate Minkowski distance between a pair of vectors by apply the formula,
( Σ|vector1i – vector2i|p )1/p
Here,
vector1 is the first vector
vector2 is the second vector
p is an integer
Below is the implementation in R to calculate Minkowski distance by using a custom function.
R
# R program to illustrate how to # calculate Minkowski distance # using a custom function # Custom function to calculate Minkowski distance calculateMinkowskiDistance <- function (vect1, vect2, p) { # Initializing answer variable as 0 answer <- as.integer (0) # Iterating over the length of the vector # Using for-in loop for (index in 0 : length (vect1)) { # temp stores the absolute difference raised to power p temp = as.integer ( abs (vect1[index] - vect2[index]) ^ p) # Updating answer variable answer = sum (temp, answer) } # The final answer would be answer raised to # power 1 / p answer = answer ^ (1 / p) # Return the answer return (answer) } # Initializing a vector vect1 <- c (1, 3, 5, 7) # Initializing another vector vect2 <- c (2, 4, 6, 8) # Set p equal to 4 p <- as.integer (1) # Call the function to calculate MinkowskiDistance distance = calculateMinkowskiDistance (vect1, vect2, p) # Print the calculated distance print ( paste ("The Minkowski distance between vect1\ and vect2 having the value of p = ",p, " is", distance )) # Set p equal to 5 p <- as.integer (2) # Call the function to calculate MinkowskiDistance distance = calculateMinkowskiDistance (vect1, vect2, p) # Print the calculated distance print ( paste ("The Minkowski distance between vect1\ and vect2 having the value of p = ",p, " is", distance )) # Set p equal to 5 p <- as.integer (3) # Call the function to calculate MinkowskiDistance distance = calculateMinkowskiDistance (vect1, vect2, p) # Print the calculated distance print ( paste ("The Minkowski distance between vect1\ and vect2 having the value of p = ",p, " is", distance )) # Set p equal to 5 p <- as.integer (4) # Call the function to calculate MinkowskiDistance distance = calculateMinkowskiDistance (vect1, vect2, p) # Print the calculated distance print ( paste ("The Minkowski distance between vect1 \ and vect2 having the value of p = ",p, " is", distance )) |
Output:
How to Calculate Minkowski Distance in R?
In this article, we are going to see how to calculate Minkowski Distance in the R Programming language.