Example 2: Using crossdist()

In this example, We are going to determine the distance between two points by using the crossdist() function available in R. The spatstat .geom package in R can be installed using the following command : 

install.packages("spatstat.geom")

 The crossdist() function is used to calculate pairwise distances between two different sets of points. 

Syntax: crossdist(x1, y1, x2, y2)

Parameters :

  • x1, y1: Numeric vectors indicating the coordinates of the first set of points.
  • x2, y2: Numeric vectors indicating the coordinates of the second set of points.

The distance between the two points indicative of their coordinates is calculated according to the formula: √((x2 – x1)2 + (y2 – y1)2)

R




library("spatstat.geom")
# Declaring coordinates of points
# First point
x1 = 2
y1 = 1
  
# Second point
x2 = 3
y2 = 1
  
# Printing distance between both points
dist = crossdist(x1, y1, x2, y2)
print("Distance between points")
print(dist)


Output:

[1] "Distance between points" 
      [,1] 
[1,]    1

In the above code, firstly we have defined two coordinates using variables x1, y1, x2, and y2 after that compute the distance between these two coordinates by passing these variables as arguments in crossdist() function.



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.

Similar Reads

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 :...

Example 2: Using crossdist()

...

Contact Us