Reputation: 797
I have two data frames. One is a Spatial Polygon and the other is a Spatial Points dataframe. Unfortunately I can't reproduce the entire example here but the Spatial Polygon looks like this:
head(electorate)
ELECT_DIV STATE NUMCCDS ACTUAL PROJECTED POPULATION OVER_18 AREA_SQKM SORTNAME
Adelaide SA 318 0 0 0 0 76.0074 Adelaide
Aston VIC 191 0 0 0 0 99.0122 Aston
Ballarat VIC 274 0 0 0 0 4651.5400 Ballarat
Banks NSW 229 0 0 0 0 49.3189 Banks
Barker SA 343 0 0 0 0 63885.7100 Barker
Barton NSW 234 0 0 0 0 44.1112 Barton
As you can see it's the spatial polygon for the Australian electorate. The second data frame is a Spatial points dataframe with longitude and latitude for polling places. It looks like this -
head(ppData)
State PollingPlaceID PollingPlaceNm Latitude Longitude
1 ACT 8829 Barton -35.3151 149.135
2 ACT 11877 Bonython -35.4318 149.083
3 ACT 11452 Calwell -35.4406 149.116
4 ACT 8794 Canberra Hospital -35.3453 149.099
5 ACT 8761 Chapman -35.3564 149.042
6 ACT 8763 Chisholm -35.4189 149.123
My goal is to try and match each polling place (PollingPlaceID) to the appropriate electoral division (ELECT_DIV). There will be many polling places within each division. It's no problem to plot them over each other. It seems only natural that R will also let me add a new vector to my polling place data frame (ppData) which assigns each polling place the electorate (ELECT_DIV) it falls within.
I know I can extract the coordinates for each ELECT_DIV from electorate with coordinates(electorate)
but I'm not sure that actually helps. Any advice?
Upvotes: 4
Views: 3460
Reputation: 59970
You need over
from sp
and you can use it like this:
require( sp )
ID <- over( SpatialPoints( ppData ) , electorate )
ppData@data <- cbind( ppData@data , ID )
This returns a data.frame
where each row relates to the first argument (each of your polling points) and is the data from the polygon that the point fell in. You can just cbind them afterwards and you now have the polygon data that relates to each point.
Upvotes: 3