问题
I have a shape file of a road network and another shape-file containing area boundaries. Is there any better code that I can use to get length of roads that lies inside each polygon? This Question was asked earlier with the difference that I want to use R instead of QGIS. I tried:
intersec=intersect(roads,Polygon)
road_length=tapply(intersec$length, intersec$polygon, sum)
This works, but the problem is that the intersection does not divide the length of the roads, that cross to Polygons, but doubles them in the intersec file and assigns the full length of those roads to both Polygons.
How I found out about that Problem: There is no error message, but the following proove tells me that something is wrong:
a=sum(roads$length) and b=sum(intersec$length)
a and b do not have same length -> a is smaller than b.
回答1:
I actually did this for a project about 8 months ago.
I had been getting into the sf
way of dealing with spatial data, and so my solution uses Classes, Methods, and functions from that package.
First, I made sure both my roads
and shapes
had the same coordinate-reference-system (CRS) by using sf::st_transform
on one of them. Then I used sf::st_intersection()
to find the intersections, and used sf::st_length()
on the result to get the lengths. You may need to aggregate the lengths at this point, depending on whether your roads were combined into one super-multi-line or if each road is its own object. The following gives the gist of what I think ought to work:
sf::st_intersection(road, shape) %>% # Find the intersections, which should all be points or multilines
dplyr::mutate(len_m = sf::st_length(geom)) %>% # Find the length of each line
dplyr::group_by(SHAPE_COLUMNS) %>% # Here you need to insert all the columns from your shapes
dplyr::summarize(len_m = sum(len_m))
来源:https://stackoverflow.com/questions/56993193/road-length-within-polygons-in-r