sf icon indicating copy to clipboard operation
sf copied to clipboard

When using `separate_wider_delim()` function remove `sf` class and returns `tibble`

Open benjaminhlina opened this issue 11 months ago • 1 comments

When using separate_wider_delim() with a sf object, the function misbehaves and returns a tibble. If using separate() the class of the sf object is retained. The same issue was documented in issue https://github.com/tidyverse/tidyr/issues/1495 but no reprex was provided. I had originally made the issue report on the {tidyr} repo, see https://github.com/tidyverse/tidyr/issues/1498, but was recently informed that is likely due to an issues with {sf} not supporting these newer versions of separate_ functions. This is using v1.3.0 of {tidyr} and {sf} v1.0-15 and see reprex.

# load packages 
suppressPackageStartupMessages({
  library(crawl) # loaded for example sf object 
  library(sf) # load sf 
  library(tidyr) # load for separate functions  
})

# load harbour seal data 
data("harborSeal_sf")

# check out the sf object 
class(harborSeal_sf)
#> [1] "sf"         "data.frame"
# make up fake column to separate 

harborSeal_sf$fake <- "test_1"
# now use separate_wide_delim 

error <- harborSeal_sf |>
  separate_wider_delim(cols = fake, names = c("fake", "num"), delim = "_")
class(error)
#> [1] "tbl_df"     "tbl"        "data.frame"
# returns tibble not an sf object so it changes the object's class 

# if we use separate it keeps the objects class 
no_error <- harborSeal_sf |>
  separate(col = fake, into = c("fake", "num"), sep = "_")

class(no_error)
#> [1] "sf"         "data.frame"

Created on 2024-03-14 with reprex v2.1.0

benjaminhlina avatar Mar 14 '24 13:03 benjaminhlina

Since the function uses tidyr::unpack() internally, we'd need to wait for tidyr to make pack()/ unpack() S3 methods and sf could provide its own method then. Not much sf can do without underlying S3 method.

Would have to wait for https://github.com/tidyverse/tidyr/pull/1372 to be merged

Edit: there would still be work required in sf afterwards to define pack(<sf>) and unpack(<sf>)

olivroy avatar Apr 04 '24 14:04 olivroy