![]() |
VOOZH | about |
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|.
In R Manhattan distance is calculated with respect to vectors. The Manhattan distance between the two vectors is given by,
Σ|vect1i - vect2i|
where,
For example, we are given two vectors, vect1 as (3, 6, 8, 9) and vect2 as (1, 7, 8, 10). Their Manhattan distance is given by, |3 - 1| + |6 - 7| + |8 - 8| + |9 - 10| which is equal to 4.
Below is the implementation using two vectors of equal length:
Example 1:
Output:
[1] "Manhattan distance between vect1 and vect2 is: " [1] 4
Example 2:
If the two vectors have unequal length then the compiler gives a warning message. Below is the implementation using two vectors having unequal lengths.
Output:
👁 ImageR 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:
Output:
👁 ImageExample 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.
Output:
👁 Image