I have a data.frame with lat long coordinates:
df<-data.frame(
lat=c(40, 30, 40.864),
lon=c(0, 20, 1.274)
)
And the border of a country (Spain),
library(raster)
border <- getData("GADM",country="Spain",level=0)
I would like to select for df
only the points inside the border
.
How can I do this?
Note: in my reproducible example, df
, the first entry point is inside, the second is clearly outside and the third is outside but close to the coast.
While I believe the post that I referred to answers this question, I think some clarification is needed; hence, posting an answer.
To find the intersection of two geographic feature, we need to have the same projection. sp library helps us to do so. Make sure to put longitude and latitude in the right place:
sp::SpatialPoints(c(my_point$long,my_point$lat),proj4string=CRS(proj4string(my_raster)))
Using rgeos library we can check if there is an intersection between two spatial dataset/feature:
rgeos::gContains(my_raster,my_projected_point)
So, here is how it works for the OP's example: