Last active
March 2, 2017 04:52
-
-
Save mdmadhu/172c0025d979b12babbb42b11ef26536 to your computer and use it in GitHub Desktop.
Creates a subset of eBird data (.txt, after download and unzipping archive) that fall within a particular region of interest whose vertices are specified (see Arguments section below for how the vertices are to be specified)
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
# MD Madhusudan, mdm@ncf-india.org, Nature Conservation Foundation, 2017-03-02 | |
# Creates a subset of eBird data (.txt, after download and unzipping archive) that fall within a particular region of interest whose vertices are specified (see Arguments section below for how the vertices are to be specified) | |
eBirdData_SpatialSubset <- function(eBirdDataFileFullPath, AoIVertices, ReturnSpatialObject=FALSE){ | |
# ARGUMENTS | |
# eBirdDataFileFullPath: must be a full path to the filename, and placed within quotes | |
# AoIVertices: vertices of a POLYGON describing the area of interest in the form | |
# "76 12, 77 12, 77 13, 76 13, 76 12", where each comma-separated pair of | |
# values represents the longitude-latitude coordinates of each vertex. NOTE | |
# THAT THE FIRST PAIR OF VALUES MUST REPEAT AS THE LAST PAIR IN ORDER TO | |
# CLOSE A POLYGON | |
# ReturnSpatialObject: if FALSE (default), returns object of class "data.frame"; | |
# if TRUE, returns an object of the class "SpatialPointDataFrame" | |
# dependencies | |
require (readr) | |
require(sp) | |
require(rgeos) | |
# helper function to create a spatial polygon from vertices | |
createAoI <- function(vertices){ | |
require(rgeos) | |
polystring <- paste("POLYGON((",vertices,"))", sep = "") | |
temp <- readWKT(polystring, p4s = CRS("+proj=longlat +datum=WGS84")) | |
return(temp) | |
} | |
# read in full dataset | |
eBlist <- read_delim(eBirdDataFileFullPath, "\t", escape_double = FALSE, trim_ws = TRUE) | |
# convert the eBird data and area-of-interest vertices to spatial objects | |
aoi <- createAoI(AoIVertices) | |
eBlistSPDF <- SpatialPointsDataFrame( | |
coords = cbind(eBlist$LONGITUDE, eBlist$LATITUDE), | |
data = eBlist, | |
proj4string = CRS("+proj=longlat +datum=WGS84") | |
) | |
# return subset for area-of-interest as a spatial index of all spatial data points | |
eBlistSpatialSubset <- eBlistSPDF[aoi,] | |
# optional recasting of data to return either data.frame or SpatialPointsDataFrame | |
ifelse( | |
isTRUE(ReturnSpatialObject)==TRUE, | |
return(eBlistSpatialSubset), | |
return( | |
within( | |
as.data.frame( | |
eBlistSpatialSubset | |
), | |
rm(coords.x1, coords.x2 | |
) | |
) | |
) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment