4

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

Gilles San Martin
  • 4,224
  • 1
  • 18
  • 31

1 Answers1

6

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.

www
  • 38,575
  • 12
  • 48
  • 84
  • 1
    Great ! Exactly what I needed. I did not thougth about the functional form of `st_geometry<-`. But thanks to you I also just discovered another function that I overlooked that works very similarly : `st_set_geometry(SF, NULL)`. Could you please add it to your reply ? – Gilles San Martin Sep 06 '17 at 23:25
  • @Gilles Thanks for sharing the use of `st_set_geometry`. I have added this information to the post. – www Sep 07 '17 at 00:49
  • 1
    The normal (R) way of using replacement functions (those ending in `<-`) is `st_geometry(nc) <- NULL`, which is understood as "replace the geometry of `nc` with `NULL`, i.e., remove it". – Edzer Pebesma Sep 28 '17 at 15:00
  • @EdzerPebesma Thanks for your comments, Prof. Pebesma! I agree that `st_geometry(nc) <- NULL` should be interpreted as "replacement", not "removal". – www Sep 28 '17 at 16:53
  • 5
    Also possible with `st_drop_geometry(nc)` – radek Jan 09 '19 at 03:59