I have points on a QGIS map, and want to determine the distance between each of the points in R. Each Unique ID is a tree. The coordinates are UTM coordinates (x = East, y = North)
My dataset looks like this:
Unique_ID | EW_X. | EW_Y |
---|---|---|
45 | 573500 | 775011 |
49 | 572224 | 774700 |
70 | 573573 | 775200 |
71 | 573573 | 775200 |
What formula would I use so I can get an output that describes the distance between each tree, looking like this (where x is the distance between each tree):
Unique_ID | 45 | 49 | 70 | 71 |
---|---|---|---|---|
45 | x | x | x | |
49 | x | x | x | |
70 | x | x | x | |
71 | x | x | x |
Or perhaps if it is more simple, repeated rows (e.g. 45 against 49, 45 against 70, 45 against 71; and etc. with each repetition being a new row)
With tidyverse
and sf
, and to get the distance matrix in meters, try:
library(tidyverse)
library(sf)
df <- tibble(
Unique_ID = c(45L, 49L, 70L, 71L),
EW_X = c(573500L, 572224L, 573573L, 573573L),
EW_Y = c(775011L, 774700L, 775200L, 775200L))
sf_trees <- st_as_sf(x = df, coords = c("EW_X", "EW_Y"),
crs = 3857) # Note that I am using WGS 84 Pseudo Mercator. If you know the UTM zone you could be more specific with the csr/epsg code
tb_distance <- st_distance(sf_trees, sf_trees, ) %>% # The following 3 lines are optional.
as_tibble() %>%
set_names(nm = df$Unique_ID) %>%
bind_cols(tibble(Unique_ID = as.character(df$Unique_ID)), . )
tb_distance
# A tibble: 4 x 5
Unique_ID `45` `49` `70` `71`
<chr> [m] [m] [m] [m]
1 45 0 1313. 203. 203.
2 49 1313. 0 1439. 1439.
3 70 203. 1439. 0 0
4 71 203. 1439. 0 0