Sf: Convenience function to access non-spatial fields

Created on 23 Feb 2017  路  8Comments  路  Source: r-spatial/sf

Is there a convenience function to extract the non-spatial fields of a feature collection akin to the data slot in sp (e.g. x@data)? Something that explicitly drops any geometry data from the feature collection and returns a simple data.frame:

st_just_data <- function(x) {
  df <- as.data.frame(x)
  df_sfc_cols <- sapply(df, function(i) inherits(i, "sfc"))
  df[, !df_sfc_cols]
}

Is this something useful? Is there a better way of doing this?

Most helpful comment

(the more elegant way if you want to do it "by hand", which I learned very recently, is to use setdiff:

nc[setdiff(names(nc), attr(nc, "sf_column"))]

note that all this assumes there is only _one_ geometry list-column, which is the current assumption of sf objects)

All 8 comments

I also wrote my own function for this. What I found crucial though is to retain the data frame structure in the output, hence I would suggest the following:

geompos <- which(names(x) == attr(x, "sf_column"))
return(data.frame(x)[, -geompos, drop = FALSE])

In general, I think this could be a useful function.

You can use st_geometry(nc) <- NULL.

(the more elegant way if you want to do it "by hand", which I learned very recently, is to use setdiff:

nc[setdiff(names(nc), attr(nc, "sf_column"))]

note that all this assumes there is only _one_ geometry list-column, which is the current assumption of sf objects)

Very elegant. I assume setdiff will preserve the data.frame class?
If so, I will update my function accordingly, thanks!

Sorry, the right incantation would be

x = as.data.frame(nc)[setdiff(names(nc), attr(nc, "sf_column"))]

since otherwise [.sf is used, which makes the geom sticky. But my first suggestion is shorter, and uses the sf api.

The original proposal of @sboysel btw removes _all_ geometry columns.

Multiple geom columns are discussed in https://github.com/edzer/sfr/issues/183

+1 for having this as a convenience function.

Was this page helpful?
0 / 5 - 0 ratings