Skip to content

Instantly share code, notes, and snippets.

@allenaven
Created November 29, 2015 18:13
Show Gist options
  • Save allenaven/98a18f9e82f3899026fb to your computer and use it in GitHub Desktop.
Save allenaven/98a18f9e82f3899026fb to your computer and use it in GitHub Desktop.
Thin an input point layer (e.g., animal telemetry locations) based on a user-specified grid for output to a SDM routine. Set up to use ESRI shapefiles, this can be modified.
# Allen Aven November 2015
# Function to thin a point input layer according to an input raster
require(sp)
require(rgdal)
require(raster)
require(dismo)
pt_thin <- function(infile, grid=grid, n_points=5) {
dsn=dirname(infile)
layer_name=str_replace(basename(infile), '.shp', '')
output_layer_name = paste0(layer_name, '_thinned')
# Read the input shapefile
in_pt <- readOGR(dsn=dsn, layer=layer_name)
# Check for projection agreement between points and grid. If not, transform points.
if(!identical(showEPSG(proj4string(grid)), showEPSG(proj4string(in_pt)))) {
in_pt <- spTransform(in_pt, CRS(proj4string(grid)))
}
# Thin the points
thinned_coords <- dismo::gridSample(xy=in_pt, r=grid, n=n_points)
# Handle the output
out_sp <- data.frame(x=thinned_coords[,1], y=thinned_coords[,2], dataset=output_layer_name)
coordinates(out_sp) <- data.frame(x=out_sp$x, y=out_sp$y)
crs(out_sp) <- CRS(proj4string(grid))
# Finally write the resulting shapefile to disk, same directory as input files
writeOGR(out_sp, dsn=dsn, layer=output_layer_name,
driver='ESRI Shapefile', overwrite_layer=TRUE)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment