rdplyrr-sf

dplyr::filter on sf object: Error in `vec_size()`: ! `x` must be a vector, not a <sfc_POLYGON/sfc> object


I loaded and filtered a geojson file (https://downtownrecovery.com/downtowns-original.geojson) using the code

library(dplyr); library(geojsonsf)
orig <- geojson_sf("downtowns-original.geojson")

orig %>%
  filter(city == "San Francisco") 

It worked with R 4.2 and dplyr 1.1.1, but with R 4.3 and dplyr 1.1.3 (and vctrs 0.6.4) I get the error below.

Error in `vec_size()`:
! `x` must be a vector, not a <sfc_POLYGON/sfc> object.
---
Backtrace:
     ▆
  1. ├─new %>% filter(city == "San Francisco")
  2. ├─dplyr::filter(., city == "San Francisco")
  3. ├─dplyr:::filter.data.frame(., city == "San Francisco")
  4. │ ├─dplyr::dplyr_row_slice(.data, loc, preserve = .preserve)
  5. │ └─dplyr:::dplyr_row_slice.data.frame(.data, loc, preserve = .preserve)
  6. │   ├─dplyr::dplyr_reconstruct(vec_slice(data, i), data)
  7. │   │ └─dplyr:::dplyr_new_data_frame(data)
  8. │   │   ├─row.names %||% .row_names_info(x, type = 0L)
  9. │   │   └─base::.row_names_info(x, type = 0L)
 10. │   └─vctrs::vec_slice(data, i)
 11. └─vctrs:::stop_scalar_type(`<fn>`(`<s_POLYGO>`), "x", `<fn>`(vec_size()))
 12.   └─vctrs:::stop_vctrs(...)

What is the issue and is there anything I should do to resolve it?


Solution

  • Not sure what the issue is - something to do with the changes in the vctrs package when updated to v0.6.4 - but if you load the sf package your code works. Perhaps it has something to do with the dplyr command aliases in sf (https://r-spatial.github.io/sf/reference/tidyverse.html?q=filter.sf#ref-usage)?

    library(dplyr)
    #> 
    #> Attaching package: 'dplyr'
    #> The following objects are masked from 'package:stats':
    #> 
    #>     filter, lag
    #> The following objects are masked from 'package:base':
    #> 
    #>     intersect, setdiff, setequal, union
    # install.packages("geojsonsf")
    library(geojsonsf)
    library(sf)
    #> Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
    
    orig <- geojson_sf("~/Desktop/downtowns-original.geojson")
    
    orig %>%
      filter(city == "San Francisco")
    #> Simple feature collection with 1 feature and 1 field
    #> Geometry type: MULTIPOLYGON
    #> Dimension:     XY
    #> Bounding box:  xmin: -122.4057 ymin: 37.78431 xmax: -122.3856 ymax: 37.80667
    #> Geodetic CRS:  WGS 84
    #>            city                       geometry
    #> 1 San Francisco MULTIPOLYGON (((-122.4048 3...
    

    Created on 2023-10-19 with reprex v2.0.2