rgeometry

How to filter sp dataframes by latitude in R


Given the sp dataframe below

library(ggplot2)
library(sf)
    
geodata <- structure(list(id = c(34355L, 34358L), geometria = structure(list(
        structure(list(structure(c(-46.6666667, -46.5, -46.5, -46.6666667, 
        -46.6666667, -25.6666667, -25.6666667, -25.8333333, -25.8333333, 
        -25.6666667), dim = c(5L, 2L))), class = c("XY", "POLYGON", 
        "sfg")), structure(list(structure(c(-46.6666667, -46.5, -46.5, 
        -46.6666667, -46.6666667, -26.1666667, -26.1666667, -26.333333, 
        -26.3333333, -26.1666667), dim = c(5L, 2L))), class = c("XY", 
        "POLYGON", "sfg"))), n_empty = 0L, class = c("sfc_POLYGON", 
    "sfc"), precision = 0, bbox = structure(c(xmin = -46.6666667, 
    ymin = -26.3333333, xmax = -46.5, ymax = -25.6666667), class = "bbox"), crs = structure(list(
        input = "EPSG:4674", wkt = "GEOGCRS[\"SIRGAS 2000\",\n    DATUM[\"Sistema de Referencia Geocentrico para las AmericaS 2000\",\n        ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n            LENGTHUNIT[\"metre\",1]]],\n    PRIMEM[\"Greenwich\",0,\n        ANGLEUNIT[\"degree\",0.0174532925199433]],\n    CS[ellipsoidal,2],\n        AXIS[\"geodetic latitude (Lat)\",north,\n            ORDER[1],\n            ANGLEUNIT[\"degree\",0.0174532925199433]],\n        AXIS[\"geodetic longitude (Lon)\",east,\n            ORDER[2],\n            ANGLEUNIT[\"degree\",0.0174532925199433]],\n    USAGE[\n        SCOPE[\"Horizontal component of 3D system.\"],\n        AREA[\"Latin America - Central America and South America - onshore and offshore. Brazil - onshore and offshore.\"],\n        BBOX[-59.87,-122.19,32.72,-25.28]],\n    ID[\"EPSG\",4674]]"), class = "crs"))), row.names = 1:2, class = c("sf", 
    "data.frame"), sf_column = "geometria", agr = structure(c(id = NA_integer_), class = "factor", levels = c("constant", 
    "aggregate", "identity")))

    ggplot() + geom_sf(data=geodata,aes(fill=id))

how to create a new sp dataframe without polygons south of -26 (26°S), indicating the latitude as the limit?

example map here


Solution

  • Build a polygon containing everything above -26 deg S and filter by this polygon:

    b <- geodata |>
      sf::st_bbox()
    
    b["ymin"] <- -26.0001
    
    b <- b |>
      sf::st_as_sfc() |>
      sf::st_as_sf()
    
    geodata <- geodata |>
      sf::st_as_sf() |>
      sf::st_filter(b)
    
    ggplot() + geom_sf(data=geodata,aes(fill=id))
    

    Created on 2024-12-07 with reprex v2.1.1.9000