27

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

  • The coersion method is avalible at sf 0.4-1, what hapens when you try to call the function? – Jeffrey Evans May 4 '17 at 2:39
  • 2
    as(sf, "Spatial") – mdsumner May 4 '17 at 6:23
  • @Jeffrey Evans, Kazuhito's answer below replicates the problem (and provides a partial solition) – Simon May 4 '17 at 8:04
38

I used

 as(nc, 'Spatial')

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

  • 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 5 '17 at 7:46
  • And it is important the accepted answer will not be overlooked by future readers. – Kazuhito May 6 '17 at 2: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
8

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)
  • Is there a way to keep the dataframe intact? – Simon May 4 '17 at 8:03
  • Running as(sf, "Spatial") by @mdsumner , I confirm it produces SpatialPolygonsDataFrame, which is better for your requirement. It seems as_Spatial() takes sfc (ie geometry) only. – Kazuhito May 4 '17 at 8:08
  • 1
    This function is a method and is ment to be call using as(). It is not exported as a function object which is why, to call it directly, you need ":::". – Jeffrey Evans May 4 '17 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.