asa*_*o23 2 r spatial tigris r-sf
我正在尝试获取两个 shapefile(落在某些大都市区边界内的人口普查区)的交集。我能够成功获得相交特征,但是当我尝试将 sf_intersect 的输出转换为 SpatialPolygonsDataframe 时,出现错误:
“as_Spatial(from) 中的错误:不支持从特征类型 sfc_GEOMETRY 到 sp 的转换”
这是我的代码:
library(sf)
library(dplyr)
library(tigris)
library(sp)
#download shapefiles corresponding to metro areas
metro_shapefiles<-core_based_statistical_areas(cb = FALSE, year = 2016)
#convert to sf and filter
metro_shapefiles<-st_as_sf(metro_shapefiles)%>%filter(GEOID==31080 )
#Data for California
census_tracts_california<-tracts(state="CA",year=2016)
census_tracts_california<-st_as_sf(census_tracts_california)
#INTERSECT AND CONVERT BACK TO SP
census_tracts_intersected1<-st_intersection(census_tracts_california,
metro_shapefiles)
#back to spatial
census_tracts_intersected1<-as(census_tracts_intersected1,"Spatial")
Run Code Online (Sandbox Code Playgroud)
错误消息告诉您不能将 an 转换sfc_GEOMETRY为Spatial对象。没有sp等效的对象。
在您的交集结果中,您有多种几何图形(因此,您将sfc_GEOMETRY作为“几何图形”返回)。您可以在此处查看所有几何图形:
types <- vapply(sf::st_geometry(census_tracts_intersected1), function(x) {
class(x)[2]
}, "")
unique(types)
# [1] "POLYGON" "MULTILINESTRING" "MULTIPOLYGON"
Run Code Online (Sandbox Code Playgroud)
如果需要,您可以提取每种类型的几何图形,并将它们单独转换为 SP:
lines <- census_tracts_intersected1[ grepl("*LINE", types), ]
polys <- census_tracts_intersected1[ grepl("*POLYGON", types), ]
spLines <- as(lines, "Spatial")
spPolys <- as(polys, "Spatial")
Run Code Online (Sandbox Code Playgroud)
我在评论中提到你可以使用st_join. 但是,这可能不会给您想要的结果。在sf图书馆有几何二元谓词,比如?st_intersects,和如几何运算?st_intersection
谓词返回一个稀疏(默认)或密集矩阵,告诉您 x 的每个几何与 y 的哪个几何相交。如果在 内使用st_join它,它将返回相交的(原始)几何图形,而不是稀疏矩阵。
而操作(例如st_intersection)将计算交集,并返回新的几何图形。
谓词 ( st_intersects) 可用于内部st_join,它们将返回“相交”的原始几何图形
sf_join <- sf::st_join(census_tracts_california, metro_shapefiles, join = st_intersects)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,这给出了一个type对象
types <- vapply(sf::st_geometry(sf_join), function(x) {
class(x)[2]
}, "")
unique(types)
# [1] "MULTIPOLYGON"
## so you can convert to a Spatial object
spPoly <- as(sf_join, "Spatial")
Run Code Online (Sandbox Code Playgroud)
但是您需要决定结果st_intersect是否是您所追求的,或者您是否需要由st_intersection.
感谢用户@lbussett 对st_intersect和之间差异的描述st_intersection