find locations within certain lat/lon distance in r

后端 未结 4 1287
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 07:57

I have a gridded dataset, with data available at the following locations:

lon <- seq(-179.75,179.75, by = 0.5)
lat <- seq(-89.75,89.75, by = 0.5)
         


        
4条回答
  •  臣服心动
    2020-11-30 08:14

    The dist* functions of the geosphere package are vectorized, so you only need to prepare better your inputs. Try this:

    #prepare a matrix with coordinates of every position
    allCoords<-cbind(lon,rep(lat,each=length(lon)))
    #call the dist function and put the result in a matrix
    res<-matrix(distm(cbind(mylon,mylat),allCoords,fun=distHaversine)<=500000,nrow=length(lon))
    #check the result
    identical(res,dd2)
    #[1] TRUE
    

    As the @Floo0 answer showed, there is a lot of unnecessary calculations. We can follow another strategy: we first determine the lon and lat range that can be closer than the threshold and then we use only them to calculate the distance:

    #initialize the return
    res<-matrix(FALSE,nrow=length(lon),ncol=length(lat))
    #we find the possible values of longitude that can be closer than 500000
    #How? We calculate the distances between us and points with our same lon 
    longood<-which(distm(c(mylon,mylat),cbind(lon,mylat))<=500000)
    #Same for latitude
    latgood<-which(distm(c(mylon,mylat),cbind(mylon,lat))<=500000)
    #we build the matrix with only those values to exploit the vectorized
    #nature of distm
    allCoords<-cbind(lon[longood],rep(lat[latgood],each=length(longood)))
    res[longood,latgood]<-distm(c(mylon,mylat),allCoords)<=500000
    

    In this way, you calculate just lg+ln+lg*ln (lg and ln are the length of latgood and longood), i.e. 531 distances, opposed to the 259200 with my previous method.

提交回复
热议问题