title: Find the smallest number from a row in a matrix filtered by a value in a data frame?
body: <p>I have a dataset of locations, and I am trying to find the distance to the closest metro area. Sample:</p>
  
  <pre><code>library(SpatialEpi)
  
  df &lt;- as.data.frame(cbind(c(100124, 100460, 100484, 100676, 100820, 2608640), c(2563, 4325, 637,330, 15278, 209880), c(31.56795, 33.60575, 34.20269, 32.87949, 33.24476, 33.52775), c(-85.25130, -86.94917, -87.17785, -87.73878, -86.76102, -86.79905), c(0,0,0,0,0,1)))
  colnames(df) &lt;- c("GEOID", "population", "latitude", "longitude", "is_metro")
  </code></pre>
  
  <p>I created a distance matrix using <code>dist</code> </p>
  
  <p><code>df_dist &lt;- as.matrix(dist(latlong2grid(matrix(c(df$longitude, df$latitude), ncol = 2, nrow=nrow(df)))))</code></p>
  
  <p>Now I would like for each row to return the distance to the closest value where is_metro=1. So, for example below, in row 1, the closest value is the 5th column, but I want to return the 6th column because that is the the column where the equivalent row is <code>is_metro==1</code>. For this particular example, I would need all of these rows to show the relevant distance to row 6, but in the full dataset, I have nearly 20K records and many records where <code>is_metro==1</code>, and I would need the closest one. </p>
  
  <p><a href="https://i.stack.imgur.com/zrLXK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zrLXK.png" alt="enter image description here"></a></p>
  
  <p>I hope that all makes sense. Where do I even start? </p>