44

How do I convert an sf object back to a SpatialPolygonsDataFrame?

I am running R 3.4.0 and sf version 0.4.1. The sf documentation mentions an as_Spatial function, but this isn't available in my install (for some reason).

Simon
  • 835
  • 1
  • 7
  • 13

2 Answers2

63

I used

 as(nc, 'Spatial')

as part 2 of the vignette by Edzer Pebesma indicated (Scroll to the bottom of the page).

andschar
  • 1,255
  • 10
  • 13
  • saw it. However I figured this out only recently and I felt the urge to put it into a proper answer when seeing this question ;) – andschar May 05 '17 at 07:46
  • And it is important the accepted answer will not be overlooked by future readers. – Kazuhito May 06 '17 at 02:05
  • 1
    For this to truly work like a SPDF, I needed to do something like: tmp <-as(nc, 'Spatial'), then tmpid <- sapply(slot(tmp, "polygons"), function(x) slot(x, "ID")) then row.names(tmp) <- tmpid – Simon May 15 '17 at 11:50
  • 1
    what does 'truly work like a SPDF' mean? I see no disadvantage created by the conversion. – andschar May 15 '17 at 14:16
14

I had to use sf:::as_Spatial() as workaround.

library(sf)
nc <- st_read(system.file("shape/nc.shp", package="sf"))

# sf -> sp
nc_sp <- as_Spatial(nc$geom)      # Error: could not find function "as_Spatial"

nc_sp <- sf:::as_Spatial(nc$geom) # This works

library(sp)
plot(nc_sp)
Kazuhito
  • 30,746
  • 5
  • 69
  • 149