使用R的sf包计算不同数据集几何交集时遇错求解决方案
解决sf包st_intersection报错问题
我从UCLA选区地图网站下载shapefile文件,尝试计算不同文件中几何图形的交集面积时,出现以下错误:
Error in
[[<-.data.frame(*tmp*, attr(x, "sf_column"), value = list( :
replacement has 2 rows, data has 1
复现代码如下:
library(tidyverse) library(sf) # Downloading files temp <- tempfile() URL <- "https://cdmaps.polisci.ucla.edu/shp/districts097.zip" download.file(URL, temp) unzip(zipfile = temp) temp <- tempfile() URL <- "https://cdmaps.polisci.ucla.edu/shp/districts098.zip" download.file(URL, temp) unzip(zipfile = temp) # Reading files df0 <- st_read("districtShapes/districts097.shp") %>% select(., STATENAME, DISTRICT) %>% filter(., STATENAME == 'Alabama') df1 <- st_read("districtShapes/districts098.shp") %>% select(., STATENAME, DISTRICT) %>% filter(., STATENAME == 'Alabama') # Intersection operation x <- st_intersection(df0[df0$DISTRICT == '1', 'geometry'], df1[df1$DISTRICT == '1', 'geometry']) %>% st_area(.) %>% as.numeric(.)
错误原因
报错的核心问题是:你提取的df0[df0$DISTRICT == '1', 'geometry']仍然是带数据框结构的sf对象(仅1行数据),但两个选区几何相交后生成了2个独立的几何要素,sf无法将2个要素匹配到只有1行的数据框中,因此触发行数不匹配错误。
解决方法
有两种可行的修改方式:
方式1:提取纯几何对象(sfc类型)
直接用st_geometry()提取几何列,得到单纯的几何集合(无数据框结构),相交后不会受行数限制:
# 提取纯几何对象 geom0 <- st_geometry(df0[df0$DISTRICT == '1', ]) geom1 <- st_geometry(df1[df1$DISTRICT == '1', ]) # 计算交集面积(若有多个交集区域,会返回每个区域的面积) x <- st_intersection(geom0, geom1) %>% st_area() %>% as.numeric() # 如果需要总面积,直接求和 total_area <- sum(x)
方式2:保留sf对象,计算总面积
直接对两个sf对象执行相交操作,再将所有交集区域的面积求和:
# 相交后计算总面积 x <- st_intersection(df0[df0$DISTRICT == '1', ], df1[df1$DISTRICT == '1', ]) %>% st_area() %>% sum() %>% as.numeric()
内容的提问来源于stack exchange,提问作者DOS
相关产品推荐
相关产品推荐

