提问者:小点点

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


我有数百万个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 

有没有更快/更好的方法来做到这一点?谢谢!


共1个答案

匿名用户

有两个类似的问题。它们在我上面的评论中。问题是问如何从坐标中获取国家名称。在这里,OP询问哪种是完成任务的更快方法。

根据帖子,我们有三个选择。

    < li >在此问题中使用自定义函数; < li >使用< code>geonames包;或者 < li >使用< code>map包中的< code>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