What is the dist() function in R?

Overview

The dist() function in R computes the distance between the given rows of an input data matrix. It returns a distance matrix computed by any of the specified methods for measuring distance.

Syntax

dist(vect, method = ” “, diag = TRUE or FALSE, upper = TRUE or FALSE)
Syntax for the dist() function

Parameters

The dist() function takes the following parameter values:

  • vect: This is a numeric matrix, data frame, or dist object.
  • method: This is the method to be used for measuring the distance. The method can be "canberra", "binary", "euclidean", "maximum", "manhattan", or "minkowski". This parameter must take any of the listed methods.
  • diag: This takes a logical value (TRUE or FALSE), specifying if the diagonal of the output matrix should be returned by print.dist or not.
  • upper: This takes a logical value (TRUE or FALSE) specifying if the upper triangle of the output distance matrix should be returned by print.dist or not.

Return value

The dist() function returns an object of class dist.

Code example

# Creating the vector obects
a = c(3, 1, 2)
b = c(4, 0, 3)
c = c(5, 4, 3)
# Using the rbind() function to row bind the vectors into a single matrix
mymatrix <- rbind(a, b, c)
# Implementing the dist() function to calculate the manhattan distance between the rows of the matrix
dist(mymatrix, method = "manhattan", diag=TRUE, upper=TRUE)
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources