Creating a distance matrix from a list of coordinates in R

coordinates, distance-matrix, euclidean-distance, r

Solution

Here's a simple example:

farms <- data.frame(lat=runif(3), lng=runif(3))
dist(farms, diag=T, upper=T)

          1         2         3
1 0.0000000 0.9275424 0.6092271
2 0.9275424 0.0000000 0.3891079
3 0.6092271 0.3891079 0.0000000

Problem

I have a csv file with a list of co-ordinate positions for over 2000 farms, with the following structure; ``` FarmID | Latidue | Longitude | ------ |---------|-----------| 1 | y1 | x1 | 2 | y2 | x2 | 3 | y3 | x3 | ``` ....... I want to to create a Euclidean Distance Matrix from this data showing the distance between all farm pairs so I get a resulting matrix like: ``` 1 | 2 | 3 | -----------|---------|-----------| 1 0 | 2.236 | 3.162 | 2 2.236 | 0 | 2.236 | 3 3.162 | 2.236 | 0 | ``` With many more farms and coordinates in the data frame I need to to be able to somehow iterate over all of the farm pairs and create a distance matrix like the one above. Any help on how to do this in R would be appreciated. Thank you!

Original source