Skip to content

Instantly share code, notes, and snippets.

@jhollist
Created October 14, 2014 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhollist/d972ab858f77a1515c90 to your computer and use it in GitHub Desktop.
Save jhollist/d972ab858f77a1515c90 to your computer and use it in GitHub Desktop.
function to interactively select and extract features from an `SpatialPolygons` or `SpatialPoints` object
extract_spatial<-function(in_spatial,over_poly=NULL,plot_result=FALSE){
plot(in_spatial)
message("Select at least 3 points to define the extent")
coords<-locator() %>%
data.frame()
poly<-rbind(coords,coords[1,]) %>%
Polygon() %>% list() %>%
Polygons(ID=1) %>% list() %>%
SpatialPolygons(proj4string=CRS(proj4string(in_spatial)))
idx<-over(poly,in_spatial,returnList=TRUE) %>% unlist()
if(plot_result){
plot(in_spatial[idx,])
plot(poly,add=T)
}
return(in_spatial[idx,])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment