Reputation: 13
I'm working with Polygons and Lines, now I want to count how many Lines intersect each Polygon.
I can intersect them, but I don't understand how to count the intersections.
inter <- intersect(district_sp, osm_maj_roads)
district_sp
is the spatial polygon. osm_maj_roads
is a spatial line object.
This way I get a complete new spaial polygon, but all I really want is a vector with the number of intersections.
Upvotes: 0
Views: 786
Reputation: 2132
Do you really get a new spatial object when you use st_intersects
? It should return a sparse index list. st_intersection
should return a new spatial object.
library(sf)
somePolygons <- st_transform(st_read('/temp/GIS/test/polygons.shp'), 3577)
someLines <- st_transform(st_read('/temp/GIS/test/linestrings.shp'), 3577)
i <- st_intersects(someLines, somePolygons)
print(i)
Sparse geometry binary predicate list of length 4, where the predicate was 'intersects'
1: (empty)
2: 2
3: 1, 3
4: 1, 2, 3
# Get a vector with the number of polygons each line intersects with:
print(sapply(i, length))
[1] 0 1 2 3
Upvotes: 1
Reputation: 13
I don't understand why nobdy answered, I had a hard time finding what I needed to do. In the end I used the aggregate funtion. roads_agg <- aggregate(x = osm_roads["osm_id"], by = polygon_shp, FUN = length) this gives me a vector with the rows being the like the polygons and the value in them the number of intersections. Hope this helps somebody ;)
Upvotes: 0