I am writing a script in r to determine the closest weather station to an object. Except, when running my code it automatically returns the weather station three (indicated by Cam in Table Station) being closest to all objects which is not the case. Any ideas why this is the case? I would also like to get the station name instead of just the index if possible.

Code:

```
 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 Table:

```
Station Lat Lon
SF  37.7749 -122.4194
CH  41.8781 -87.6298
Cam 52.2053 -0.1218

```

Object Table:

```
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

```