
Get Spatial Subset of Data
get_spatial_subset.RdFilters a data frame of spatial points to include only those within a specified polygon.
Arguments
- polygon
An
sfobject representing the polygon to use for filtering.- data
A data frame containing spatial point data with latitude and longitude columns.
- lat_col
A character string specifying the name of the latitude column in the data frame.
- lon_col
A character string specifying the name of the longitude column in the data frame.
- crs
An integer specifying the Coordinate Reference System (CRS) for the input points (default is 4326).
- verbose
A logical value indicating whether to display messages about processing (default is
FALSE).
Details
This function converts a data frame with latitude and longitude columns into an sf object, checks for CRS consistency
between the input polygon and the data, and performs a spatial filtering operation to retain only the points
that fall within the given polygon.
If the CRS of the input polygon does not match the CRS of the data, the polygon is transformed to match the data's CRS.
Examples
if (FALSE) { # \dontrun{
library(sf)
# Example polygon
polygon <- st_as_sf(data.frame(
id = 1,
geometry = st_sfc(st_polygon(list(matrix(c(
-10, -10,
10, -10,
10, 10,
-10, 10,
-10, -10
), ncol = 2, byrow = TRUE))))
), crs = 4326)
# Example data frame
data <- data.frame(
id = 1:5,
lat = c(0, 5, -15, 20, -5),
lon = c(0, 5, 15, -20, -5)
)
# Subset points within the polygon
filtered_data <- get_spatial_subset(polygon, data, lat_col = "lat", lon_col = "lon", verbose = TRUE)
print(filtered_data)
} # }