I have object1
with polygons and object2
with lines. I am looking for a way in R (preferably with the package sf) to calculate the sum of line lengths from object2
for each polygon in object1
.
The resulting object should have the same features as object1
, but with as additional attribute the length of the lines from object2
across each polygon of object1
.
Best Answer
Read some data:
Gives:
Key operation is intersection:
Which returns this:
which is all the intersections of the lines with the polygons and ID attributes from the source lines and polygons. Map:
So to get the length in each polygon, sum up the line segment lengths by polygon ID, which is ID.0:
Polygons that don't have any lines in them are missing from this list, so you can't simply put them in the vector. Also, they might be in a random order...
To put these values in the right place in the polygon object a bit of
match
and indexing:Then you can do: