converting sf multipolygon to sp

348 Views Asked by At

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

There are 1 best solutions below

0
Spacedman On

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