R maps - 在地图中绘制点时过滤掉坐标

R maps - Filter coordinates out when plotting points in map

我有一个大型事件位置数据框(经度、纬度)。请参阅下面的示例:

events <- structure(list(lat = c(45.464944, 40.559207, 45.956775, 44.782831, 45.810287, 35.913357, 43.423855, 45.2359, 45.526025, 41.91371, 46.340833, 40.696482, 42.367164, 41.913701, 41.89167, 46.046206, 41.108316, 45.514132, 45.688118, 37.090387, 43.446555, 41.913712, 46.614833, 45.368825, 41.892168), lon = c(9.163453, 8.321587, 12.983347, 10.886471, 9.077844, 10.560439, 6.768272, 9.23176, 9.375761, 12.466994, 6.889444, 17.316925, 13.352248, 12.466992, 12.516713, 14.497758, 16.871019, 12.056176, 9.176543, 15.293506, 6.77119, 12.466993, 15.194904, 11.110711, 12.516085)), .Names = c("lat", "lon"), row.names = c(NA, 25L), class = "data.frame")

我只想绘制发生在给定国家(例如意大利)的事件。

下面绘制了所有事件:

library(rworldmap)
library(maps)
par(mar=c(0,0,0,0))
plot(getMap(resolution="low"), xlim = c(14,14), ylim = c(36.8,47))
points(x=events$lon, y=events$lat, pch = 19, col ='red' , cex = 0.6)

如何过滤掉国家边界之外的事件?预先感谢您的帮助和支持。

将多边形贴图分配给对象:

m = getMap(resolution="low")

将事件转换为 sp 对象 -- 首先是经度,然后是纬度:

pts = SpatialPoints(events[c(2,1)])

分配 CRS:

proj4string(pts) = proj4string(m)

在任何多边形内绘制点:

points(pts[m,], pch = 3)

select 意大利境内点数:

it = m[m$ISO_A2 == "IT",]
points(pts[it,], col = 'blue')

(这使用 sp::over,但在幕后)