从数百万个GPS坐标确定国家的最快方法[R]

从数百万个GPS坐标确定国家的最快方法[R],r,coordinates,geospatial,sp,sf,R,Coordinates,Geospatial,Sp,Sf,我有数百万个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))

我有数百万个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 
库(data.table)
#复制数据

数据有两个相似的问题。它们在我上面的评论中。问题是如何从坐标中获取国家名称。在这里,OP会询问哪种方法更快完成任务。根据帖子,我们有三个选择。一个是在这个问题中使用自定义函数。另一种方法是使用
geonames
包。另一种方法是在
map
包中使用
map.where()
。第二个选项需要一些设置。所以我刚刚测试了
map.where()
。结果如下。正如OP所说,这个功能必须更快地工作

library(maps)
set.seed(111)
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))

system.time(data[, country := map.where(x = longitude, y = latitude)])

#   user  system elapsed 
#   7.20    0.05    7.29 
库(地图)
种子(111)

我想你们已经看到了数据。这篇文章的另一个选项是使用
geonames
包。我想知道这对你是否有效。看。我测试了
map.where()
。这个功能运行得非常快。@jazzurro,谢谢你的帮助!map.where()大约快10倍。干杯如果您的大多数积分都在美国、加拿大、俄罗斯、澳大利亚。。。您可以手动找到仅包含给定国家/地区的最大矩形,并对其进行预过滤,这可以大大加快速度,除非提议的包已经进行了此类优化。