title: Determining the weather station closest to a object
body: <p>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.</p>
  
  <p>Code:</p>
  
  <pre><code> earth.dist &lt;- function (long1, lat1, long2, lat2)
   {
   rad &lt;- pi/180
   a1 &lt;- lat1 * rad
   a2 &lt;- long1 * rad
   b1 &lt;- lat2 * rad
   b2 &lt;- long2 * rad
   dlon &lt;- b2 - a2
   dlat &lt;- b1 - a1
   a &lt;- (sin(dlat/2))^2 + cos(a1) * cos(b1) * (sin(dlon/2))^2
   c &lt;- 2 * atan2(sqrt(a), sqrt(1 - a))
   R &lt;- 6378.145
   d &lt;- R * c
   return(d)
   }
  
  
   for (i in 1:length(Object$Lat))
   {
       for (j in 1:length(Station$Lat))
       {
           a[j] &lt;- earth.dist(Station$Lon[j], Station$Lat[j], Object$Lon[i], Object$Lat[i])
       }
       index &lt;- which(min(a) %in% a)
       Object$Station[i] = Station$Station[index]
   }
  </code></pre>
  
  <p>Station Table:</p>
  
  <pre><code>Station Lat Lon
  SF  37.7749 -122.4194
  CH  41.8781 -87.6298
  Cam 52.2053 -0.1218
  </code></pre>
  
  <p>Object Table:</p>
  
  <pre><code>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
  </code></pre>