Susie
Susie

Reputation: 197

How to quickly identify if points (latitude & longitude) are within one country or not?

This is the location data frame by longitude &latitude.

library(data.table)
a1=seq(10,60,1);a2=seq(70,140,1)
a3=lapply(a1,function(i){res=data.table(i,a2)})
pretb=rbindlist(a3,fill=T);

I want to confirm every points within China range or not by below code.
after running, find totally used nearly 40 minutes to get result.

library(maps)
> Sys.time()
[1] "2017-06-23 12:54:12 CST"
>   bb=apply(pretb,1,function(ce){
+     aa=map.where(database="world", ce[3], ce[2])
+   })
>   bb

> Sys.time()
[1] "2017-06-23 13:35:56 CST"

Actually, can not use such a long time to execute code. Is there any fast way to get judgement or other better function or package more efficient ?

Upvotes: 0

Views: 353

Answers (1)

Alex Deckmyn
Alex Deckmyn

Reputation: 1037

It is much, much more efficient to run map.where() once on the whole list of points, rather than on every point separately (and as I said in the comment, in v3.2 of maps the code is much more efficient as well, sometimes 100x faster). Just pass vectors with all latitudes (y) and longitudes (x) of the list:

z <- map.where(database="world", x=pretb$a2, y=pretb$i)

Takes about 1 second to run.

If you are not able to update to the latest version of 'maps', you can also speed up the code a lot by loading the world map into memory (rather than reading it from disk):

myworld <- map("world", fill=TRUE, plot=FALSE)
z <- map.where(myworld, y=pretb$i, x=pretb$a2)

map.where() before 3.2 was very inefficient in reading various polygons from the map data stored on disk. This is most noticeable if your R libraries are installed on a network drive which takes longer to respond than local drives.

Upvotes: 2

Related Questions