r-spatial / sf

Simple Features for R
https://r-spatial.github.io/sf/
Other
1.33k stars 293 forks source link

[feature] function to get `sf_column` attribute #2435

Open JosiahParry opened 1 week ago

JosiahParry commented 1 week ago

As a package developer I often want to grab the geometry column from an sf object. However, it is not safe to assume that the column is called geometry. For this reason I grab the sf_column attribute. This is done via attr(x, "sf_column"). It would be great if there were a helper function to get this. For example:

sf_column <- function(x) {
  if (!inherits(x, "sf")) {
    stop("Expected an `sf` object")
  }
  attr(x, "sf_column")
}

x <- sf::st_sf(
  x = 1, foo = sf::st_sfc(sf::st_point(c(0, 0)))
)

sf_column(x)
#> [1] "foo"

sf_column(1L)
#> Error in sf_column(1L): Expected an `sf` object

sf_column(list())
#> Error in sf_column(list()): Expected an `sf` object
edzer commented 1 week ago

As a package developer I often want to grab the geometry column from an sf object.

For that, sf provides the generic st_geometry().

JosiahParry commented 1 week ago

Perhaps I should edit the text, I often want to get the geometry column name. st_geometry() is indeed useful for accessing the underlying sfc. But often i need to know which column is the geometry column by name or position and the sf_column attribute helps with that .

A quick search shows that the top hit is in fact a function called sf_column() for the same purpose! There are a good handful of folks who have built something similar https://github.com/search?q=%22sf_column%22&type=code