How to Apply the dist() Function in R (2 Examples)

In this tutorial, I’ll show how to apply the dist function in the R programming language.

Creation of Exemplifying Data

set.seed(94658194)        # Example matrix
my_matrix <- matrix(runif(15),
                    nrow = 3)
my_matrix                 # Returning example matrix
#           [,1]      [,2]      [,3]       [,4]      [,5]
# [1,] 0.7445896 0.8082464 0.3445148 0.42680115 0.6917136
# [2,] 0.2564643 0.7346047 0.4734162 0.05443584 0.0167147
# [3,] 0.1069663 0.6271011 0.8974123 0.37756418 0.5370574

Example 1: Calculate Euclidean Distance with dist() Function

dist(my_matrix)           # Using dist() function
#           1         2
# 2 0.9244373          
# 3 0.8783027 0.7673642

Example 2: Calculate Maximum Distance with dist() Function

dist(my_matrix,           # Using dist() function
     method = "maximum")
#           1        2
# 2 0.6749989          
# 3 0.6376233 0.5203427

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top