r – Convert Geometry Set to Simple Features Collection Using `sf` in R

rsfst-geometry

How can geometry set objects be converted to simple features collection objects with the package sf in R? I want to add attribute data to the geometry but am prevented from doing so because geometry set excludes including data.

Converting simple features collection to geometry set is done using st_geometry, but what is the equivalent in reverse? See sample code below:

#load sample data set
nc <- st_read(system.file("shape/nc.shp", package="sf"))
#Simple feature collection with 100 features and 14 fields
#geometry type:  MULTIPOLYGON
#etc

#convert to geometry collection
nc_geom<-st_geometry(nc)
#Geometry set for 100 features 
#geometry type:  MULTIPOLYGON
#etc

Best Answer

I think you want to create a spatial data frame with st_sf:

nc2 = st_sf(geom=nc_geom)
class(nc2)
#[1] "sf"         "data.frame"

Then you can add extra columns:

nc2$ID=1:length(nc_geom)
nc2
#Simple feature collection with 100 features and 1 field
#geometry type:  MULTIPOLYGON
#dimension:      XY
#bbox:           xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
#epsg (SRID):    4267
#proj4string:    +proj=longlat +datum=NAD27 +no_defs
#First 10 features:
#                             geom ID
#1  MULTIPOLYGON (((-81.47276 3...  1
#2  MULTIPOLYGON (((-81.23989 3...  2
#3  MULTIPOLYGON (((-80.45634 3...  3