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
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),]