Created
November 29, 2015 18:13
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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