英文:
converting sf multipolygon to sp
问题
我有一个包含多边形的sf对象,我需要将其转换为sp对象。似乎使用sf转换函数无法正常工作。
我尝试过以下方法:
library(absmapsdata)
library(sp)
library(sf)
vic_sa4 <- sa42021
class(vic_sa4)
vic_sa4_sp <- as_Spatial(vic_sa4)
tmp <- as(vic_sa4, 'Spatial')
vic_sa4_sp <- sf:::as_Spatial(st_geometry(vic_sa4))
as(vic_sa4, "Spatial")
但是都给我返回了这个错误 - 但几何图形确实存在!如何解决这个问题?
在选择函数 'addAttrToGeom' 的方法时评估参数 'x' 时出错:sp类不支持空几何图形
英文:
I have sf object with multipolygons which i need to convert to sp object. It does not seem to work with sf conversion functions.
I tried
library(absmapsdata)
library(sp)
library(sf)
vic_sa4<-sa42021
class(vic_sa4)
vic_sa4_sp <- as_Spatial(vic_sa4)
tmp <-as(vic_sa4, 'Spatial')
vic_sa4_sp <- sf:::as_Spatial(st_geometry(vic_sa4))
as(vic_sa4, "Spatial")
it all gives me this error - but the geometry is indeed there! how to fix this?
error in evaluating the argument 'x' in selecting a method for function 'addAttrToGeom': empty geometries are not supported by sp classes
答案1
得分: 2
需要删除具有空几何形状的项目。您可以使用 st_is_empty
进行测试。这里有一些由过多的负缓冲导致的空几何形状示例:
p = st_point(c(1,1))
pv = st_sfc(p,p,p,p,p)
bv = st_buffer(pv, c(1,1,0,-1,2))
d = st_sf(bv)
测试:
> st_is_empty(d)
[1] FALSE FALSE TRUE TRUE FALSE
删除:
dnonempty = d[!st_is_empty(d),]
转换:
> library(sp) ; library(raster) # raster的漂亮sp打印方法
> as(dnonempty, "Spatial")
class : SpatialPolygonsDataFrame
features : 3
extent : -1, 3, -1, 3 (xmin, xmax, ymin, ymax)
crs : NA
variables : 0
英文:
You need to get rid of the items with empty geometry. You can test with st_is_empty
. Here's a thing with some empty geometries caused by excessive negative buffering into nothingness:
p = st_point(c(1,1))
pv = st_sfc(p,p,p,p,p)
bv = st_buffer(pv, c(1,1,0,-1,2))
d = st_sf(bv)
> d
Simple feature collection with 5 features and 0 fields (with 2 geometries empty)
Geometry type: POLYGON
Dimension: XY
Bounding box: xmin: -1 ymin: -1 xmax: 3 ymax: 3
CRS: NA
bv
1 POLYGON ((2 1, 1.99863 0.94...
2 POLYGON ((2 1, 1.99863 0.94...
3 POLYGON EMPTY
4 POLYGON EMPTY
5 POLYGON ((3 1, 2.997259 0.8...
Test:
> st_is_empty(d)
[1] FALSE FALSE TRUE TRUE FALSE
Remove:
dnonempty = d[!st_is_empty(d),]
Convert:
> library(sp) ; library(raster) # raster's nice sp print method
> as(d, "Spatial")
Error in h(simpleError(msg, call)) :
error in evaluating the argument 'x' in selecting a method for function 'addAttrToGeom': empty geometries are not supported by sp classes: conversion failed
> as(dnonempty, "Spatial")
class : SpatialPolygonsDataFrame
features : 3
extent : -1, 3, -1, 3 (xmin, xmax, ymin, ymax)
crs : NA
variables : 0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论