# How to calculate the distance of points to line in R?

I need the distance from each point of the object found to the transect line. 'id' is a research transect, and 'obj.id' is the object found. in this case, 1 object was found in transect A and 2 objects in transect B. So how do I calculate the distance between objects towards its transect lines? I have only come this far:

``````points <- data.frame(
'id' = c('A','B','B'),
'obj.id' = c('x1', 'x2', 'x3'),
'x' = c(60, 65, 66),
'y' = c(130, 134, 135)
)

lines <- data.frame(
'id' = c('A','B'),
'x1' = c(58, 64),
'y1' = c(128, 132),
'x2' = c(61, 67),
'y2' = c(131, 135)
)

rows <- split(lines, seq(nrow(lines)))
lines <- lapply(rows, function(row) {
lmat <- matrix(unlist(row[2:5]), ncol = 2, byrow = TRUE)
st_linestring(lmat)
})

lines <- st_sfc(lines)
lines <- st_sf('id'=c('A','B'),'geometry'=lines)

join <- inner_join(points, lines, by='id')
``````

I tried dist2Line, st_distance with sf packages, but haven't found the right method.

If you coerce your points to an sf class object then you can use the `st_distance` function.

Here we recreate your example data

``````library(sf)

points <- data.frame('id' = c('A','B','B'),
'obj.id' = c('x1', 'x2', 'x3'),'x' = c(60, 65, 66),
'y' = c(130, 134, 135))

lines <- data.frame('id' = c('A','B'),
'x1' = c(58, 64), 'y1' = c(128, 132),
'x2' = c(61, 67), 'y2' = c(131, 135))

rows <- split(lines, seq(nrow(lines)))
lines <- st_sfc(lapply(rows, function(row) {
lmat <- matrix(unlist(row[2:5]), ncol = 2, byrow = TRUE)
st_linestring(lmat)}))
lines <- st_sf('id'=c('A','B'),'geometry'=lines)
``````

This is where we coerce the points data.frame to an sf object and then use `st_distance`

``````points <- st_as_sf(points, coords = c("x", "y"),
agr = "constant")

st_distance(points, lines)
``````

Here is the equivalent of `dplyr::inner_join` using sf objects

``````sf::st_join(points, lines, by='id')
``````
• Thank you for your help
– mnf
May 11 '20 at 10:12