title: Efficient way to compute scores within data.table by group
body: <p>I have the following <code>data.table</code> and I am looking to calculate by group (<code>id</code>) the smallest (<code>min</code>) jarowinkler score by all other members of that group. I have a simple nested loop that can compute this, though looking for a more efficient method.</p>
  
  <pre><code>library(data.table)
  # install.packages("stringdist")
  library(stringdist)
  
  # Create `data.table`
  dt &lt;- data.table(id = c(1,1,2,2,2,3,3,3,3,4,4,4), 
                  var = c("a","a","kyle","kyle","kile","rage","page","cage","","asd","fdd","xzx"))
  
  # Add a numeric empty score variable         
  dt[, "score" := as.numeric()]       
  # Create a unique id within each group         
  dt[, uid := sequence(.N), by = id]
  
  dt
  #     id  var score uid
  #  1:  1    a    NA   1
  #  2:  1    a    NA   2
  #  3:  2 kyle    NA   1
  #  4:  2 kyle    NA   2
  #  5:  2 kile    NA   3
  #  6:  3 rage    NA   1
  #  7:  3 page    NA   2
  #  8:  3 cage    NA   3
  #  9:  3         NA   4
  # 10:  4  asd    NA   1
  # 11:  4  fdd    NA   2
  # 12:  4  xzx    NA   3
  </code></pre>
  
  <p>The current, but slow method:</p>
  
  <pre><code># Loop over all unique id's
  for(i in unique(dt$id)){
     # Loop over each member and compute lowest stringdist 
     for(j in 1:nrow(dt[id == i])){
          dt[id == i &amp; uid == j, "score" := min(stringdist(dt[id == i &amp; uid == j, var], 
                                                dt[id == i &amp; uid != j, var],
                                                method = "jw"))]
      }
  }
  
  dt[]
  #     id  var     score uid
  #  1:  1    a 0.0000000   1
  #  2:  1    a 0.0000000   2
  #  3:  2 kyle 0.0000000   1
  #  4:  2 kyle 0.0000000   2
  #  5:  2 kile 0.1666667   3
  #  6:  3 rage 0.1666667   1
  #  7:  3 page 0.1666667   2
  #  8:  3 cage 0.1666667   3
  #  9:  3      1.0000000   4
  # 10:  4  asd 0.4444444   1
  # 11:  4  fdd 0.4444444   2
  # 12:  4  xzx 1.0000000   3
  </code></pre>