微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试总结 R 中网格单元内的线长

如何解决尝试总结 R 中网格单元内的线长

我正在尝试计算 R 中网格单元内的线长总和。我一直将其用作参考 https://gis.stackexchange.com/questions/289350/calculate-sum-of-line-lengths-in-r

我遇到的问题是,当我使用 st_make_grid 创建网格时,当我将线相交长度与网格匹配时,没有 ID 列。我尝试使用 as.Spatial 将网格转换为 SpatialpolygonsDataFrame 以便我可以添加列,但是 st_length 和 st_intersections 将不起作用,因为网格不再是“sf”对象。对此最好的解决方法是什么?

解决方法

您需要通过 sf::st_as_sf() 将网格从 sfc 转换为 sf 对象

考虑这个例子,它建立在众所周知且深受喜爱的 nc.shp 数据集上,该数据集随 {sf} 一起提供

library(sf)
library(dplyr)

shape <- st_read(system.file("shape/nc.shp",package="sf")) %>%  
  summarise() %>% 
  st_geometry() %>% 
  st_cast("POLYGON") %>% 
  st_cast("LINESTRING")

# a line around North Carolina - to get a line object
plot(shape)

enter image description here

grid <- st_make_grid(x = st_bbox(shape),n = c(30,10)) %>% 
  st_as_sf() %>% # this is the part!
  mutate(id = 1:nrow(.)) # now tis possible to add a row id

intersection <- st_intersection(grid,shape) %>% 
  mutate(lenght = st_length(.)) %>% 
  st_drop_geometry() # complicates things in joins later on


grid <- grid %>% 
  left_join(intersection,by = "id")

plot(grid["lenght"])

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。