【发布时间】:2019-03-25 10:38:49
【问题描述】:
我有数百万个 GPS 坐标,想快速添加坐标国家的一列。
我目前的方法有效,但速度极慢:
library(data.table)
#REPRODUCE DATA
data <- data.table(latitude=sample(seq(47,52,by=0.001), 1000000, replace = TRUE),
longitude=sample(seq(8,23,by=0.001), 1000000, replace = TRUE))
#REQUIRED PACKAGES
if (!require("sp")) install.packages("sp")
if (!require("rworldmap")) install.packages("rworldmap")
if (!require("sf")) install.packages("sf")
library(sp)
library(rworldmap)
library(sf)
#CURRENT SLOW FUNCTION
coords2country = function(points,latcol,loncol){
countriesSP <- getMap(resolution='low')
pointsSP <- st_as_sf(points,coords=c(loncol,latcol),crs=4326)
pointsSP<- as(pointsSP,"Spatial")
# use 'over' to get indices of the Polygons object containing each point
indices = over(pointsSP, countriesSP)
# return the ADMIN names of each country
indices$ADMIN
#indices$ISO3 # returns the ISO3 code
#indices$continent # returns the continent (6 continent model)
#indices$REGION # returns the continent (7 continent model)
}
#SLOW!
> system.time(data[,country:=coords2country(data,"latitude","longitude"),])
user system elapsed
121.293 7.849 130.226
有没有更快/更好的方法来做到这一点?谢谢!
【问题讨论】:
-
我想你见过this post。这篇文章的另一个选择是使用
geonames包。我想知道这是否适合你。 -
见this question。我测试了
map.where()。此功能运行速度非常快。 -
@jazzurro,感谢您的帮助! map.where() 大约快 10 倍。干杯!
-
如果您的大部分点都在美国、加拿大、俄罗斯、澳大利亚...您可以手动找到仅包含给定国家/地区的最大矩形,并对那些进行预过滤,即除非提议的软件包已经进行了这种优化,否则可以大大加快速度。
标签: r coordinates geospatial sp sf