Reputation: 4127
I have a shapefile named "ind_adm" and a SpatialPointsDataFrame called "pnts". The "pnts" contains points generated at random, and some of the points overlap with the polygon. See picture below.
Now, I want do do a point in polygon analysis, i.e. I want to find out which points lie inside the gray polygon representing the boundary of India. For this I am using the over() function in the sp library.
pt.in.poly <- sp::over(ind_adm, pnts, fn = mean) #do the join
However, the output I am getting is
>pt.in.poly
values
0 6.019467
I should actually get the index of the points that are "in" the polygon.
Where am I going wrong?
Upvotes: 37
Views: 40346
Reputation: 41
You could also use the st_intersection
function from the sf
package:
library(sf)
ind_adm <- st_as_sf(ind_adm)
(24047 is the EPSG code for India)
pnts <- st_as_sf(pnts) %>% st_set_crs(., 24047)
kept_points <- st_intersection(ind_adm, pnts)
Upvotes: 4
Reputation: 319
Found this concise and intuitive syntax for over:
pnts[ind_adm,]
from this Intro document
Upvotes: 30
Reputation: 13817
You can use point.in.poly
fom spatialEco
package. It "intersects point and polygon feature classes and adds polygon attributes to points".
library(spatialEco)
new_shape <- point.in.poly(pnts, ind_adm)
Upvotes: 10
Reputation: 59980
You should not supply a function. You are aggregating the attribute values of your points over the geometry of the polygon, (i.e. the number returned is the mean
of the attribute of the points that fall within the polygon). In addition you have your x
and y
the wrong way round for what you want to do. Should be...
over( pnts , ind_adm , fn = NULL)
Upvotes: 30