Extract data without geometries from `sf` objects like in `sp@data`

2.9k views Asked by At

Probably a very basic question but I found nothing in the documentation of Simple Features R package.

I'm looking for the native sf function to extract on the fly all the columns of an sf object without the geometries. Just like SP@data with sp objects.

The following function does the job but I would prefer to use a native function :

st_data <- function(SF) { SF[, colnames(SF) != attr(SF, "sf_column"), drop = TRUE]}

A typical use is when I want to merge two sf dataset by attribute (merge does not work with two sf objects) : merge(SF1, st_data(SF2)).

In that case it would be impractical to use st_geometry(SF2) <- NULL because it does not work "on the fly" and I don't want to permanently drop the geometry column and SF2[,1:5,drop=T] is impractical too because I have to look into the object to see where the geometry column is.

Using : sf_0.5-4 - R 3.4.1

1

There are 1 answers

5
www On BEST ANSWER

We can use the st_geometry<- function and set the geometry to be NULL.

library(sf)

nc <- st_read(system.file("shape/nc.shp", package="sf"))

nc_df <- `st_geometry<-`(nc, NULL)

class(nc_df)
[1] "data.frame"

As you can see, nc_df is a dataframe now, so I think you can do the following for your example.

merge(SF1, `st_geometry<-`(SF2, NULL))

Update

As Gilles pointed out, another function, st_set_geometry, can also achieve the same task. It is probably a better choice since using st_set_geometry does not need the use of "``" and "<-" to enclose the st_geometry function.