r-spatial / sf

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

a new function to convert sf to data.frame with list column #371

Closed faridcher closed 7 years ago

faridcher commented 7 years ago

there are so many popular functions in r that don't support list column yet. I find myself repeatedly having to remove the geometry column of a sf object . so a simple function like this would be very useful:

drop_geom <- function(x)
{
  if(inherits(x,"sf"))
    ret <- x[,setdiff(names(x),attr(x,'sf_column')),drop=T]
  else
    ret <- x

  class(ret) <- 'data.frame'
  return(ret)
}

which could be used as:

str(x <- st_sf(a=3:4,b=5:6, geom=st_sfc(st_point(1:2),st_point(3:4))))
str(df <- drop_geom(x))

This function could also be used in sf::as.data.frame.sf() context to convert sf object to "pure" data.frame (i.e. without a list column).

thanks

Nowosad commented 7 years ago

My approach is to use st_set_geometry(x, NULL), but I really like your function. Maybe it should be called st_drop_geometry?

faridcher commented 7 years ago
st_drop_geometry <- function(x) {
  if(inherits(x,"sf")) {
      x <- st_set_geometry(x, NULL)
      class(x) <- 'data.frame'
  }
  return(x)
}

also works. The call is by @edzer .

edzer commented 7 years ago

As I've expressed earlier, the benefit of convenience here does not weight against the cost of the more complex API. An option might be to add this function as an example to the help page of sf, so users who really fancy this can add it to their own scripts.

Wylie-Fuller commented 4 years ago

To convert sf objects to tables without geometry columns, I've been using: simple_feature %>% as_tibble() %>% dplyr::select(-geometry)

Functions requiring tables can be chained in the middle of the pipe, and the output converted back to an sf object, e.g. simple_feature %>% as_tibble() %>% .[!duplicated(.[, "Camera_Site"]),] %>% st_as_sf()