Creating column of intersected objects

210 Views Asked by At

I have two objects overlapping each other:

  • Multipolygons
  • Polylines

Like this:

enter image description here

I need to add a column in the Multipolygons object with the intersected rows from the other object, something like this:

enter image description here

Any ideas how to achieve this using SF library in R?

1

There are 1 best solutions below

0
On BEST ANSWER

Given polygons and lines as sf class objects polys and lins:

> st_intersects(polys, lins)
Sparse geometry binary predicate list of length 3, where the predicate
was `intersects'
 1: 1, 4
 2: 1, 2, 3
 3: 3, 4

This is a list with one element per polygon where the element is a vector of line indexes that intersect the polygon.

You can add this as a "list-column" to the polygons data frame:

> polys$inter = st_intersects(polys, lins)
> polys
Simple feature collection with 3 features and 3 fields
Geometry type: POLYGON
Dimension:     XY
Bounding box:  xmin: -1067397 ymin: 6387427 xmax: 423059 ymax: 7406499
Projected CRS: WGS 84 / Pseudo-Mercator
  id a                       geometry   inter
1  1 A POLYGON ((-1067397 7294588,...    1, 4
2  2 B POLYGON ((-462058.4 7099591... 1, 2, 3
3  3 C POLYGON ((-451884.6 6436600...    3, 4

Note that list columns break the clean tabular nature of data frames and I'd usually avoid them, it can make further data handling messy...