How to use dist() function In R Language
R provides an inbuilt function using which we can find the Manhattan distance between each unique pair of vectors in a 2-dimensional vector.
Syntax:
dist(2dVect, method = “manhattan”)
Parameters:
- 2dVect: two-dimensional vector
- method: the distance measure to be used. This can be one of “euclidean”, “maximum”, “manhattan”, “canberra”, “binary”
Return type:
It return an object of class “dist”
Example 1:
Below is the implementation to find Manhattan distance using dist() function:
R
# Initializing a vector vect1 < - c (1, 16, 8, 10, 100, 20) # Initializing another vector vect2 < - c (1, 7, 18, 90, 50, 21) # Initializing another vector vect3 < - c (3, 10, 11, 40, 150, 210) # Initializing another vector vect4 < - c (2, 1, 4, 7, 8, 10) # Initializing another vector vect5 < - c (1, 4, 8, 3, 100, 104) # Initializing another vector vect6 < - c (3, 7, 11, 23, 110, 114) # Row bind vectors into a single matrix twoDimensionalVect < - rbind (vect1, vect2, vect3, vect4, vect5, vect6) print ( "Manhattan distance between each pair of vectors is: " ) cat ( "\n\n" ) # Calculate Manhattan distance between vectors # using built in dist method # By passing two-dimensional vector as a parameter # Since we want to calculate manhattan distance between # each unique pair of vectors # That is why we are passing manhattan as a method dist (twoDimensionalVect, method= "manhattan" ) |
Output:
Example 2:
Note that the length of all the vectors presented under the 2-dimensional vector is required to be the same otherwise, the R compiler produces a compiler-time error.
R
# Initializing a vector vect1 <- c (4, 3, 5, 7, 8, 2, 10, 12) # Initializing another vector vect2 <- c (5, 9, 4, 9, 7, 17) # Initializing another vector vect3 <- c (3, 10, 9, 11, 13, 12) # Initializing another vector vect4 <- c (4, 7, 6, 12, 10, 12) # Initializing another vector vect5 <- c (3, 5, 12, 10, 1, 17) # Initializing another vector vect6 <- c (4, 3, 1, 8, 7, 2) # Using rind function to bind vectors in a 2-d vector # Note that all vectors are not of the same length twoDimensionalVect <- rbind (vect1, vect2, vect3, vect4, vect5, vect6) print ( "Manhattan distance between each pair of vectors is: " ) cat ( "\n\n" ) # Calculate Manhattan distance between vectors # using built in dist method # By passing two-dimensional vector as a parameter # Since we want to calculate Manhattan distance # between each pair of vectors # That is why we are passing "manhattan" as a method dist (twoDimensionalVect, method = "manhattan" ) |
Output:
How to Calculate Manhattan Distance in R?
Manhattan distance is a distance metric between two points in an N-dimensional vector space. It is defined as the sum of absolute distance between coordinates in corresponding dimensions.
For example, In a 2-dimensional space having two points Point1 (x1,y1) and Point2 (x2,y2), the Manhattan distance is given by |x1 – x2| + |y1 – y2|.