R语言 将sf多边形转换为sp多边形

t8e9dugd  于 2023-06-27  发布在  其他
关注(0)|答案(1)|浏览(193)

我有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")

这一切都给了我这个错误-但几何确实存在!如何解决这个问题?

error in evaluating the argument 'x' in selecting a method for function 'addAttrToGeom': empty geometries are not supported by sp classes
roejwanj

roejwanj1#

您需要删除具有空几何体的项目。你可以用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)

> 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...

测试:

> st_is_empty(d)
[1] FALSE FALSE  TRUE  TRUE FALSE

删除:

dnonempty = d[!st_is_empty(d),]

转换:

> 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

相关问题