r-spatial / sf

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

bbox class is not detectable in S4 methods #2448

Closed sigmafelix closed 1 month ago

sigmafelix commented 1 month ago

st_bbox() output has class that is reported when class() is run, however, when a S4 method tries to utilize this information, I encounter a "no definition for class bbox" error.

Reproducible example

library(sf)
dd <- st_bbox(c(xmin = 16.1, xmax = 16.6, ymax = 48.6, ymin = 47.9), crs = st_crs(4326))
class(dd)
[1] "bbox"

setGeneric("detect_bbox", function(x){})
[1] "detect_bbox"
setMethod("detect_bbox", signature = c(x = "bbox"), function(x){class(x)})
# in method for ‘detect_bbox’ with signature ‘x="bbox"’: no definition for class “bbox”

With sf class object, S4 method works properly:

library(sf)
ncsf_path <- system.file("shape/nc.shp", package = "sf")
ncsf <- st_read(ncsf_path)

setGeneric("detect_sf_col", function(x){})
setMethod("detect_sf_col", signature = c(x = "sf"), function(x) names(x))
detect_sf_col(ncsf)
# [1] "AREA"      "PERIMETER" "CNTY_"     "CNTY_ID"   "NAME"      "FIPS"
# [7] "FIPSNO"    "CRESS_ID"  "BIR74"     "SID74"     "NWBIR74"   "BIR79"
#[13] "SID79"     "NWBIR79"   "geometry"
edzer commented 1 month ago

You may need to S4 register the class, using setOldClass("bbox"), so that S4 can dispatch on it. It would be reasonable to assume sf does this, but that has not happened so far:

$ grep setOld *R
init.R:setOldClass("sf")
init.R:setOldClass(c("sfc_POINT", "sfc"))
init.R:setOldClass(c("sfc_MULTIPOINT", "sfc"))
init.R:setOldClass(c("sfc_LINESTRING", "sfc"))
init.R:setOldClass(c("sfc_MULTILINESTRING", "sfc"))
init.R:setOldClass(c("sfc_POLYGON", "sfc"))
init.R:setOldClass(c("sfc_MULTIPOLYGON", "sfc"))
init.R:setOldClass(c("sfc_GEOMETRY", "sfc"))
init.R:setOldClass(c("sfc_GEOMETRYCOLLECTION", "sfc"))
init.R:setOldClass("sfg")
init.R:setOldClass("crs")
sgbp.R:setOldClass("sgbp")
sp.R:setOldClass("XY")
sigmafelix commented 1 month ago

Thank you for the prompt response and the new push.