Nea*_*sch 3 r geospatial coordinates r-sp r-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))
#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
Run Code Online (Sandbox Code Playgroud)
有更快/更好的方法吗?谢谢!
有两个类似的问题。他们在我上面的评论中。问题在询问如何从坐标中获取国家/地区名称。在这里,OP正在询问哪种是执行任务的更快方法。根据帖子,我们有三个选择。一种是在此问题中使用自定义函数。另一个是使用geonames包装。另一种是map.where()在map包装中使用。第二个选项需要一些设置。所以我刚测试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
Run Code Online (Sandbox Code Playgroud)