title: dplyr rowwise, find closest (latitude, longitude) record in a second data frame
body: <p>Would like to assign each zip code to its closest ghcnd weather collection station.  Using <code>library(zipcode)</code> and the list of ghcnd stations available from NOAA (<a href="ftp://ftp.ncdc.noaa.gov/pub/data/ghcn/" rel="nofollow noreferrer">ftp://ftp.ncdc.noaa.gov/pub/data/ghcn/</a>)</p>
  
  <p>Trying to use <code>dplyr</code>; using a <code>rowwise %&gt;% mutate()</code>. All rows are assigned the same value from the lookup table.</p>
  
  <pre><code>#small selection of zip codes from library(zipcode)
  zip_samp &lt;- "zip latitude longitude
  30002 33.77212 -84.26491
  30003 33.96035 -84.03786
  30004 34.11918 -84.30292
  30005 34.08004 -84.21929
  39885 31.71000 -84.34000
  39886 31.73000 -84.60000
  39897 30.90000 -84.32000
  39901 33.89125 -84.07456
  "
  zip &lt;- read.table(text=zip_samp, header=TRUE)
  
  #two example stations
  station_samp &lt;- "id lat long
  US1GADK0015 33.7794 -84.2572
  US1GAGW0024 33.8885 -84.0998
  "
  stations &lt;- read.table(text=station_samp, header=TRUE)
  </code></pre>
  
  <p>Illustrate desired output by hardcoding:</p>
  
  <pre><code>as.character(stations[which.min(distGeo(c(-84.26491, 33.77212), select(stations, long, lat))), "id"])
      [1] "US1GADK0015"
  
  as.character(stations[which.min(distGeo(c(-84.07456, 33.89125), select(stations, long, lat))), "id"])
  [1] "US1GAGW0024"
  </code></pre>
  
  <p>note these two zip codes are assigned to different station ids, but when the  same formula is applied rowwise with <code>dplyr</code>, all zip codes are assigned to a single ID. </p>
  
  <pre><code>assigned &lt;- zip %&gt;%
      select(longitude, latitude) %&gt;%
      rowwise() %&gt;%
      mutate(station =
          as.character(stations[which.min(distGeo(., select(stations, long, lat))), "id"])
      )
  
  print(assigned)
  Source: local data frame [8 x 3]
  Groups: &lt;by row&gt;
  
  # A tibble: 8 x 3
    longitude latitude     station
        &lt;dbl&gt;    &lt;dbl&gt;       &lt;chr&gt;
  1 -84.26491 33.77212 US1GADK0015
  2 -84.03786 33.96035 US1GADK0015
  3 -84.30292 34.11918 US1GADK0015
  4 -84.21929 34.08004 US1GADK0015
  5 -84.34000 31.71000 US1GADK0015
  6 -84.60000 31.73000 US1GADK0015
  7 -84.32000 30.90000 US1GADK0015
  8 -84.07456 33.89125 US1GADK0015
  </code></pre>
  
  <p>Is there an alternative to indexing inside the <code>mutate()</code> call?</p>
  
  <p><em>note, trying to avoid creating the entire distance matrix at once.  I hope computing rowwise will require fewer resources</em></p>
  
  <p>Also, there are a couple similar questions on SO, none using <code>dplyr</code> though. Hoping to figure why this application of rowwise %>% mutate isnt producing the expected results.</p>