[GIS] Extracting data.frame from simple features object in R

rsf

Is there an sf-native (i.e. "correct") way of extracting everything except the geometry column from a simple features object? This works

df <- dplyr::select(as.data.frame(sf), -geometry)

but the select( , -geometry) step feels unnecessary. Also, it doesn't remove the geometry attributes.

Best Answer

To drop the geometry column, use st_drop_geometry():

library(sf)
nc <-  st_read(system.file("shape/nc.shp", package="sf"), quiet = TRUE)
nc_df2 <- nc %>% st_drop_geometry()
class(nc_df2)
#> [1] "data.frame"

Before st_drop_geometry() was added to the sf package (in November, 2018), one could produce the same result using the st_set_geometry() function, like this:

library(sf)
nc <-  st_read(system.file("shape/nc.shp", package="sf"), quiet = TRUE)
class(nc)
#> [1] "sf"         "data.frame"

nc_df <- nc %>% st_set_geometry(NULL)
class(nc_df)
#> [1] "data.frame"