虽然我相信我提到的帖子回答了这个问题,但我认为需要澄清一下;因此,发布答案。
要找到两个地理特征的交集,我们需要有相同的投影。sp库帮助我们做到这一点。确保将经度和纬度放在正确的位置:
sp::SpatialPoints(c(my_point$long,my_point$lat),proj4string=CRS(proj4string(my_raster)))
使用rgeos库,我们可以检查两个空间数据集/特征之间是否存在交集:
rgeos::gContains(my_raster,my_projected_point)
因此,以下是它在 OP 示例中的工作方式:
library(sp) #for projection
library(raster) #for getting the border data
library(rgeos) #for finding intersection
library(tidyverse) #for illustration only
#data
border <- getData("GADM",country="Spain",level=0)
df <- data.frame(
lat=c(40, 30, 40.864),
lon=c(0, 20, 1.274)
)
#this is the part that actually check if a point is inside the border
#adapted from https://stackoverflow.com/questions/21971447
sapply(1:3,function(i)
list(id=i,
intersect= gContains(border,SpatialPoints(df[i,2:1],proj4string=CRS(proj4string(border))))))
# [,1] [,2] [,3]
# id 1 2 3
# intersect TRUE FALSE FALSE
#a map for better understanding
ggplot()+
geom_polygon(data=border, aes(x=long, y=lat, group=group),
fill=NA, color="grey50", size=0.25) +
geom_point(data=df,aes(x=lon,y=lat), color="red", size=1)