rcoordinatesdistancer-sfutm

Distance between pairs of coordinastes (UTM) in km with R


I have a dataframe with 2 pairs of UTM (32N) coordinates and I need to compute the differences in km between each of them, from origin to destination. I'm trying with sf library, using "by_element" but I obtain an error message "Error in st_distance(data, by_element = TRUE) : !missing_y non è TRUE". What's wrong? If I use it without the "by_element" option, it works and the distance matrix between all coordinates is created, but this is not what I need.

library(sf)
df <- data.frame(id = c(1,2,3), x_origin = c(642683.2, 373775,383881 ), y_origin = c(5082920, 4997274,4994504), x_dest =c(642683.3, 1126050,942763.9 ), y_dest=c(5082920, 4374481,4534235  )) 

data <- st_as_sf(df, coords = c("x_origin", "y_origin"), crs="4326" )

distances <- st_distance(data, by_element = TRUE  )

Solution

  • You have provided x (origin) to st_distance()but no y (destination). And that CRS can't be right, sf doesn't recognise EPSG code if it's a string and 4326 would suggest coordinates are in WGS84 lat/long. Assuming 32632, WGS 84 / UTM zone 32N.

    library(sf)
    df <- data.frame(id = c(1,2,3), x_origin = c(642683.2, 373775,383881 ), y_origin = c(5082920, 4997274,4994504), x_dest =c(642683.3, 1126050,942763.9 ), y_dest=c(5082920, 4374481,4534235  )) 
    origin <- st_as_sf(df, coords = c("x_origin", "y_origin"), crs=32632 )
    dest <- st_as_sf(df, coords = c("x_dest", "y_dest"), crs=32632 )
    
    (distances <- st_distance(origin, dest,  by_element = TRUE ))
    #> Units: [m]
    #>        1        2        3 
    #>      0.1 976621.1 724015.0
    

    Created on 2023-01-25 with reprex v2.0.2