I'm working with Brazilian deforestation data - specifically two sf objects:

  • A point shapefile on environmental fines (centroid of land plots that have been fined for deforestation).
  • A polygon of (unioned) municipalities.

My aim is to calculate the nearest distance from each point to the municipal boundary line. I can do this using st_distance, however I would like the distance to be negative for points that are within the municipality polygon (as in picture below). Could anyone please advise?

deforest <- st_read("Environmental_Fines.shp")
munic <- st_read("Municipalities_Union.shp")


1 Answer 1


Outine solution:

  1. Cast the polygons to lines using st_cast and compute distances of pounts to lines (otherwise you get zero for the distance of points inside polygons).

  2. Use st_intersects on the points/polygons to test if point is inside polygon, and negate the distance for those that are.

  • Thanks very much! I've just added a column to my Deforestation df with st_intersects, with value 0/1 - however it's been added in list format (integer(0) or 1). Do you know how this can be converted to an object within the df instead?
    – cstock
    May 1, 2022 at 20:45
  • st_intersects returns a list because a point could be in several polys. If you are sure this isn't the case (maybe you only have one poly) then you can compute a "is it in a poly?" with lengths(st_intersection(....)) > 0 - note use of lengths (not length) which returns zero for integer(0) when there's no intersection. Use that to make a vector to put in your data frame.
    – Spacedman
    May 2, 2022 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.