46

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

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

2 Answers 2

63

I used

 as(nc, 'Spatial')

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

4
  • 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
    Commented May 5, 2017 at 7:46
  • And it is important the accepted answer will not be overlooked by future readers.
    – Kazuhito
    Commented May 6, 2017 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
    Commented May 15, 2017 at 11:50
  • 1
    what does 'truly work like a SPDF' mean? I see no disadvantage created by the conversion.
    – andschar
    Commented May 15, 2017 at 14:16
15

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)
5
  • Is there a way to keep the dataframe intact?
    – Simon
    Commented May 4, 2017 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
    Commented May 4, 2017 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 ":::". Commented May 4, 2017 at 17:29
  • it seems the as() function is no longer in the sf package
    – mattador
    Commented Aug 16, 2022 at 14:10
  • as_Spatial(nc) will keep the dataframe intact!
    – M--
    Commented May 11, 2023 at 18:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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