Skip to content

Instantly share code, notes, and snippets.

@infinex
Created March 13, 2016 13:06
Show Gist options
  • Save infinex/43b797300d61ddfa3d8a to your computer and use it in GitHub Desktop.
Save infinex/43b797300d61ddfa3d8a to your computer and use it in GitHub Desktop.
How to intersect polygons and points in R
library(rgdal)
library(sp)
library(ggplot2)
#you have to supply your own points and polygon
postal_code<-read.csv('postalCode/postal_code.csv')
shape_rgdal <- readOGR("Planning_Area_Census2010", "Planning_Area_Census2010")
shape_rgdal<- spTransform(shape_rgdal , CRS("+proj=longlat +datum=WGS84"))
Neighborhoods <- fortify(shape_rgdal)
library(ggmap)
location <- c(103.851959, 1.290270)
location
map <- get_map(location, zoom=12,maptype='toner-lite')
p<-ggmap(map)
p + geom_polygon(aes(x=long, y=lat, group=group), fill='black', size=.2,color='green', data=Neighborhoods, alpha=1) + geom_point(aes(x=longitude,y=latitude),postal_code,size=0.01,alpha=0.1,color="yellow")
coordinates(postal_code)=c("longitude", "latitude")
crs.geo <- CRS("+proj=longlat +datum=WGS84") # geographical, datum WGS84
proj4string(postal_code) <- crs.geo # define projection system of our data
#main function to join points with polygon
df<-over(postal_code, shape_rgdal)
head(df)
aa<-cbind(postal_code@data,df,postal_code@coords)
write.csv(aa,'postalCode_with_zone.csv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment