试图总结 R 中网格单元格内的线长
Trying to summarize line lengths within grid cells in 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)
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"])
我正在尝试计算 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()
考虑这个例子,它建立在众所周知且深受喜爱的 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)
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"])