tidymodels/recipes

recipe() fails with vague error using {sf} objects

Opened this issue · 2 comments

The problem

When making a recipe using an sf object a very vague error occurs. After some thinking, the issue is quite obviously the sticky geometry column. It looks like recipes does some checking, but not enough checking of the class inheritance.

When tbl_df class is present with the sf class, recipes assumes the object is a tibble only. However, it is possible to be both an sf object and a tibble—intersectionality in S3 inheritance, amiright?

Reproducible example

nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"))
#> Reading layer `nc' from data source 
#>   `/Users/josiahparry/Library/R/arm64/4.4/library/sf/shape/nc.shp' 
#>   using driver `ESRI Shapefile'
#> Simple feature collection with 100 features and 14 fields
#> Geometry type: MULTIPOLYGON
#> Dimension:     XY
#> Bounding box:  xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
#> Geodetic CRS:  NAD27
recipes::recipe(SID74 ~ NWBIR74 + BIR79, data = nc)
#> 
#> ── Recipe ──────────────────────────────────────────────────────────────────────
#> 
#> ── Inputs
#> Number of variables by role
#> outcome:   1
#> predictor: 2

class(nc) <- c("sf", "tbl_df", "tbl", "data.frame")
recipes::recipe(SID74 ~ NWBIR74 + BIR79, data = nc)
#> Error in `recipe.data.frame()`:
#> ✖ `vars` and `roles` must have same length.
#> • `vars` has length 3
#> • `roles` has length 4

Created on 2024-11-15 with reprex v2.1.1

possible solution

One option could be to check for the presence of the sf class and remove it whenever found something along the lines of:

data <- nc

if (rlang::inherits_any(data, "sf")) {
  class(data) <- setdiff(class(data), "sf")
}


recipes::recipe(SID74 ~ NWBIR74 + BIR79, data = data)

Thank you for the report and suggestion! will get to this in the next release push

If the data class is modified, should the change be restored after a bake()?

Is there an argument for a "geometry" role for variables that arise from spatial columns? I am not sure that this fixes anything but the presence of a geometry term does leave a clue that the data is spatial even when its class has been disguised.