Example 1: Computing Euclidean Distance
The proxy library in R is used to calculate the proximities and compute them efficiently. The package can be downloaded and installed into the working space using the following command :
install.packages("proxy") library("proxy")
The dist() function can be used to compute the distance between the specified set of points. It returns the distance matrix of the specified matrix using the method that is specified as the argument.
Syntax: dist(df1, df2, method)
Parameters :
- df1 – The first data frame
- df2 – The second data frame
method – The method used to compute distance, which may be “euclidean”, “manhattan” or “maximum” distance.
R
# Importing the required library library (proxy) # creating a data frame data_frame1 = data.frame (x= c (2, 4), y= c (3, 1)) data_frame2 = data.frame (x= c (8, 2), y= c (6, 3)) print ( "Distance Matrix " ) # creating a distance matrix dist (data_frame1, data_frame2, method= "euclidean" ) |
Output:
[1] "Distance Matrix " > #creating a distance matrix > dist(data_frame1, data_frame2, method = "euclidean") [,1] [,2] [1,] 6.708204 0.000000 [2,] 6.403124 2.828427
In the above code, firstly we have defined two data frames of different coordinates and after that compute the distance between the two points using euclidean method in dist() function.
R
# Defining the point1 with x=2 and y=1 pt1 <- data.frame (x = 2, y = 1) # Defining the point 2 with x = 4 and y=1 pt2 <- data.frame (x = 10, y = 1) # Defining euclidean distance between two points euc.dist <- function (x1, x2) sqrt ( sum ((x1 - x2) ^ 2)) # Calculating euclidean distance dist<- euc.dist (pt1,pt2) print ( "Euclidean Distance" ) print (dist) |
Output:
[1] "Euclidean Distance" > dist [1] 8
Distance Between Two Sets of Points in R
In the following article, we are going to compute the distance between two sets of points in the R programming language.
In algebra, each point in the two-dimensional plane is represented by the x and y coordinates respectively. The distance between any two points can be computed using both of its coordinate points. There are a large number of in-built as well as external packages in R which can be used to compute the distance between two sets of points. In this article, we are going to use the dist() and crossdist() function to calculate the distance between two sets of points.