Find nearest points of latitude and longitude from different data sets with different length

前端 未结 5 2185
你的背包
你的背包 2020-12-19 08:24

I have two data set of different stations. The data are basically data.frames with coordinates, longitudes and latitudes. Given the first data set (or vice versa), I want to

5条回答
  •  佛祖请我去吃肉
    2020-12-19 09:09

    You can use a series of apply commands to do this. Note that the x and y in the functions refer to set1 and set2 rather than the lat lon coords - the lat lon coords are specified as p1 and p2. [NOTE: Edited to correct order of set1 and set2 in calculations - the order determines if you are calculating the value in set2 closest to each value in set 1 or vice-versa)

    distp1p2 <- function(p1,p2) {
        dst <- sqrt((p1[1]-p2[1])^2+(p1[2]-p2[2])^2)
        return(dst)
    }
    
    dist2 <- function(y) min(apply(set2, 1, function(x) min(distp1p2(x,y))))
    
    apply(set1, 1, dist2)
    

    Or if you want the station with the nearest point rather than the min distance change min to which.min in dist2()

    dist2b <- function(y) which.min(apply(set2, 1, function(x) min(distp1p2(x,y))))
    apply(set1, 1, dist2b)
    

    And to get the lat-lon for that station

    set2[apply(set1, 1, dist2b),]
    

提交回复
热议问题