我正在寫一個腳本來確定與對象最近的氣象站。除了運行我的代碼時,它會自動返回氣象站3(由Table Station中的Cam指示)與所有物體最接近的情況。任何想法,爲什麼是這種情況?如果可能的話,我還想獲得電臺名稱,而不僅僅是索引。確定離對象最近的氣象站
代碼:
earth.dist <- function (long1, lat1, long2, lat2)
{
rad <- pi/180
a1 <- lat1 * rad
a2 <- long1 * rad
b1 <- lat2 * rad
b2 <- long2 * rad
dlon <- b2 - a2
dlat <- b1 - a1
a <- (sin(dlat/2))^2 + cos(a1) * cos(b1) * (sin(dlon/2))^2
c <- 2 * atan2(sqrt(a), sqrt(1 - a))
R <- 6378.145
d <- R * c
return(d)
}
for (i in 1:length(Object$Lat))
{
for (j in 1:length(Station$Lat))
{
a[j] <- earth.dist(Station$Lon[j], Station$Lat[j], Object$Lon[i], Object$Lat[i])
}
index <- which(min(a) %in% a)
Object$Station[i] = Station$Station[index]
}
電臺表:
Station Lat Lon
SF 37.7749 -122.4194
CH 41.8781 -87.6298
Cam 52.2053 -0.1218
對象表:
Object Lat Lon
1 38.983 -123.092
2 36.941 -121.767
3 36.121 -121.084
4 38.415 -121.787
5 36.854 -121.362
6 38.651 -121.218
7 37.314 -120.386
8 36.158 -119.8514
9 38.599 -121.54
10 35.335 -120.734
11 34.841 -120.212
12 38.004 -122.02
13 37.599 -122.052
14 38.0903 -122.5267
15 37.664 -121.885
16 51.50853 -0.076132