The dist() function is used to calculate distance matrix which shows distance between rows of matrix or dataframe.

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

Method 1: Use dist() Function

dist(matrix)

The following example shows how to use dist() function in R.

Using dist() Function

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

# Define vectors
a <-c(78,85,89,96,74,75)
b <-c(65,66,64,69,70,61)
c <-c(23,25,26,19,21,18)
d <-c(45,41,35,36,39,48)

# Define matrix
matrix1 <- rbind(a,b,c,d)

# Show matrix
print(matrix1)

# Calculate distance matrix 
dist(matrix1)
  [,1] [,2] [,3] [,4] [,5] [,6]
a   78   85   89   96   74   75
b   65   66   64   69   70   61
c   23   25   26   19   21   18
d   45   41   35   36   39   48


          a         b         c
b  45.78209                    
c 150.26976 107.88420          
d 107.21474  63.91400  48.31149

Here the output shows distance matrix of matrix that we declared in above code using dist() function.