rgisr-sf

Filter polygons on coordinates


I'm currently working with a shapefile that does not contain explicit latitude and longitude coordinates. My goal is to filter out areas with latitudes above 60 degrees. I want to delete the small area in the lower right corner, but I don't have the latitude and longitude. Can anyone suggest a code to achieve this?

The shapefile look like this:

enter image description here

This is my current code:

shapefile_path <- "/Users/langbai/Desktop/lcsd000b16a_e/lcsd000b16a_e.shp"

shapefile_data <- st_read(shapefile_path)

convex_hulls_inset <- convex_hulls_with_farms %>%
  filter(lat < 60)

shapefile_inset <- shapefile_data %>%
  filter(st_coordinates(st_centroid(geometry))[, 2] < 80)

Solution

  • First, create a new column using mutate(), then filter() that column. Here's an example using the built-in nc dataset:

    library(sf)
    library(dplyr)
    library(ggplot2)
    
    # Example data
    nc <- st_read(system.file("shape/nc.shp", package = "sf"))
    
    shapefile_inset <- nc %>%
      mutate(y = st_coordinates(st_centroid(geometry))[, 2]) %>%
      filter(y < 35) %>%
      select(-y)
    
    ggplot() + 
      geom_sf(data = nc) +
      geom_sf(data = shapefile_inset, fill = "#DF536B")
    

    result