Reputation: 67
How do you convert from a MULTIPOLYGON
to a SpatialPolygonsDataFrame
in R
?
I can't find any other resources online and I attempted to discretise the same file that was a GEOMETRYCOLLECTION
, XY
and sfg
class, however, this led to a continuous loop of referencing the same polygon without accessing the individual points. I'm happy to provide any additional clarification and will appreciate any insight.
A sample of one of the outputs for the multipolygon Ref_circles
to show formatting is given as:
Ref_circles[1]
[[1]]
[[1]][[1]]
[,1] [,2]
[1,] 51.62730 4.340600
[2,] 51.62549 4.343550
[3,] 51.61800 4.357353
[4,] 51.61124 4.371529
[5,] 51.60523 4.386039
[6,] 51.59998 4.400845
...
[311,] 51.63570 4.322473
[312,] 51.62894 4.336649
[313,] 51.62730 4.340600
Upvotes: 2
Views: 5505
Reputation: 26248
My first question to you would be: why do you want to convert from an sf
object (MULTIPOLYGON) to an sp
object (SpatialPolygonDataFrame), as sf
supersedes sp
?
There are probably ways to achieve your end goal staying within the sf
library without having to do this conversion.
If you still want to do it, it will be along the lines of
library(sf)
library(sp)
## using a MULTIPOLYGON data set supplied with library(sf)
nc <- sf::st_read(system.file("shape/nc.shp", package="sf"))
## convert the geometry of the `sf` object to SpatialPolygons
spd <- sf::as_Spatial(st_geometry(nc), IDs = as.character(1:nrow(nc)))
class(spd)
# [1] "SpatialPolygons"
# attr(,"package")
# [1] "sp"
## grab the data from the sf object
df <- nc
df$geometry <- NULL
df <- as.data.frame(df)
## create the SpatialPolygonsDataFrame
spd <- sp::SpatialPolygonsDataFrame(spd, data = df)
class(spd)
# [1] "SpatialPolygonsDataFrame"
# attr(,"package")
# [1] "sp"
head(spd@data)
# AREA PERIMETER CNTY_ CNTY_ID NAME FIPS FIPSNO CRESS_ID BIR74 SID74 NWBIR74 BIR79 SID79 NWBIR79
# 1 0.114 1.442 1825 1825 Ashe 37009 37009 5 1091 1 10 1364 0 19
# 2 0.061 1.231 1827 1827 Alleghany 37005 37005 3 487 0 10 542 3 12
# 3 0.143 1.630 1828 1828 Surry 37171 37171 86 3188 5 208 3616 6 260
# 4 0.070 2.968 1831 1831 Currituck 37053 37053 27 508 1 123 830 2 145
# 5 0.153 2.206 1832 1832 Northampton 37131 37131 66 1421 9 1066 1606 3 1197
# 6 0.097 1.670 1833 1833 Hertford 37091 37091 46 1452 7 954 1838 5 1237
Upvotes: 7