To calculate manhattan distance in R, you can use dist() function with method argument or create function manually. The Manhattan distance is the sum of absolute differences in each dimension of the data points.

The following method shows how you can do it with syntax.

Method 1: Use dist() Function

dist(matrix,method="manhattan")

Method 2: Create Function Manually

manhattan_dist <- function(x, y){
     dist <- abs(x-y)
     dist <- sum(dist)
     return(dist)
}

The following example shows how to calculate manhattan distance in R.

Create Function Manually to Calculate Manhattan Distance

Let’s see how we can create function manually to calculate manhattan distance in R:

# Declare function to calculate Manhattan distance
manhattan_dist <- function(x, y){
     dist <- abs(x-y)
     dist <- sum(dist)
     return(dist)
}

# Create two vectors
x <- c(17,18,15,12,20,13)

y <- c(15,18,15,18,20,21)

# Calculate Manhttan distance
d <- manhattan_dist(x,y)

# Display distance
print(d)

Output:

[1] 16

As the output shows manhattan distance between two vectors is 16.

Use dist() Function

Let’s see how we can use dist() function in R to calculate manhttan distance:

# Declare vector
x <- c(7,8,9,4)

y <- c(5,8,9,7)

z <- c(5,7,1,2)

# Combine vector to create vector
mat <- rbind(x,y,z)

# Calculate Manhttan distance
d <- dist(mat,method="manhattan")

# Show distance
print(d)

Output:

 x  y
y  5   
z 13 14

Here the output shows Manhttan distance between matrix using dist() function.