title: Replace values in data.table by an aggregated value
body: <p>I want to calculate an aggregated value from a <code>data.table</code> and use it to replace the original values. I tried the following approach</p>
  
  <pre class="lang-r prettyprint-override"><code>library(data.table)
  (DT &lt;- data.table(grp  = rep(LETTERS[1:3], 3), 
                    val  = 1:9, 
                    val2 = rep(letters[24:26], each = 3)))
  #    grp val val2
  # 1:   A   1    x
  # 2:   B   2    x
  # 3:   C   3    x
  # 4:   A   4    y
  # 5:   B   5    y
  # 6:   C   6    y
  # 7:   A   7    z
  # 8:   B   8    z
  # 9:   C   9    z
  
  (agg &lt;- DT[, .SD[which.min(val)], grp])
  #    grp val val2
  # 1:   A   1    x
  # 2:   B   2    x
  # 3:   C   3    x
  
  DT[, val3 := "New Value"]
  agg[DT, on = "grp"][, .SD, .SDcols = !patterns("^i\\.")]
  #    grp val val2      val3
  # 1:   A   1    x New Value
  # 2:   B   2    x New Value
  # 3:   C   3    x New Value
  # 4:   A   1    x New Value
  # 5:   B   2    x New Value
  # 6:   C   3    x New Value
  # 7:   A   1    x New Value
  # 8:   B   2    x New Value
  # 9:   C   3    x New Value
  </code></pre>
  
  <p>While this approach works in this toy example I have a couple of concerns:</p>
  
  <ol>
  <li><p>I would like to avoid chaining in the first place to avoid massive copying of unused columns (my real dataset is rather big <code>2e5 x 200</code>) Quote from <a href="https://cran.r-project.org/web/packages/data.table/vignettes/datatable-faq.html#why-does-xy-return-all-the-columns-from-y-too-shouldnt-it-return-a-subset-of-x" rel="nofollow noreferrer">data.table FAQ 1.10</a>:</p>
  
  <blockquote>
    <p>We therefore strongly encourage X[Y, j] instead of X[Y]</p>
  </blockquote>
  
  <p>Putting the <code>.SD</code> part into the <code>j</code> slot in the first subset, won't work</p>
  
  <pre class="lang-r prettyprint-override"><code>agg[DT, .SD, on = "grp", .SDcols = !patterns("^i\\.")]
  # Error in do_patterns(colsub, names_x) : Pattern not found: [^i\.]
  </code></pre></li>
  <li>The <code>patterns</code> approach feels a bit hackish and relies on the assumption that <code>data.table</code> will always prefix the columns from <code>Y</code> with <code>i.</code>. If the package maintainers would change that for whatever reason my code would break.</li>
  <li>I am still learning <code>data.table</code> and I want to learn what is the most "idiomatic" way of solving this in <code>data.table</code></li>
  </ol>
  
  <p>How can I solve this problem while avoiding to make unnecessary copies to save resources? </p>
  
  <p><em>Note.</em> For what it matters: I do not want to change the values in <code>DT</code> by reference.  </p>