title: R function error `replacement has length zero` trouble?
body: <p>I am defining the following function to identify the nearest other individuals within the same group (both their distance and their id):</p>
  <pre><code>get_min_opp_dist &lt;- function(position_table) {
    
    min_dist &lt;- vector(mode = &quot;double&quot;, length = nrow(position_table))
    min_dist_idx &lt;- vector(mode = &quot;logical&quot;, length = nrow(position_table))
  
    for (i in 1:nrow(position_table)) {
      x &lt;- position_table$x[i]
      y &lt;- position_table$y[i]
      team &lt;- position_table$team[i]
      
      if (team == &quot;ball&quot;) {
        next()
      }
      
      idx &lt;- position_table$team != team &amp; position_table$team != &quot;ball&quot;
      min_dist[i] = min(sqrt((x - position_table$x[idx])^2 + (y - position_table$y[idx])^2))
      
      Id_sub &lt;- position_table$Id[idx]
      
      min_dist_idx[i] &lt;- Id_sub[which.min(sqrt((x - position_table$x[idx])^2 + (y - position_table$y[idx])^2))]
  
    }
    
    position_table$opp_min_dist &lt;- min_dist
    position_table$opp_min_dist_idx &lt;- min_dist_idx
  
    
    
    return(position_table)
    
  }
  </code></pre>
  <p>I then run the function using:</p>
  <pre><code>data &lt;- data %&gt;%
    group_by(var1, var2, var3, var4)
  data &lt;- group_split(data) 
  data &lt;- lapply(data, get_min_opp_dist) 
  data &lt;- bind_rows(data) 
  </code></pre>
  <p>However, this throws the following error when running lapply:</p>
  <pre><code>Error in min_dist_x[i] &lt;- x_sub[which.min(sqrt((x - position_table$x[idx])^2 +  : 
    replacement has length zero
  Called from: FUN(X[[i]], ...)
  </code></pre>
  <p>I have tried debugging this, but haven't had any luck. This function works with a small chunk of data, but when I apply it to my entire data, it breaks. Because the dataset is so large (far too large to provide for MRE), it takes 20 minutes just to get to the debugger. I'm out of ideas. What does the error even mean and how can I fix it?</p>