 <p>I think this is what you want:</p> <pre><code>dat[ , `:=`(var1 = var[1L], var2 = var2[1L]), by = .(id, year)] </code></pre> <p>As a function you'd have to do something like:</p> <pre><code>fn_const &lt;- function(data, id, year, constant){ data[ , (constant) := .SD[1L], by = c(id, year), .SDcols = constant] data } </code></pre> <p>Note that this won't assign to <code>dat</code>, so you'll have to use something like <code>dat &lt;- fn_const(...)</code>, which is probably not ideal (making copies). Instead, why not eliminate <code>data</code> as an argument:</p> <pre><code>fn_const&lt;-function(id, year, constant){ dat[ , (constant) := .SD[1L], by = c(id, year), .SDcols = constant] } </code></pre> <p>Now simply running <code>fn_const(id, year, constant)</code> will assign <code>constant</code> by reference to <code>dat</code> with no copies necessary.</p> <p>TBH I don't really see any benefit of writing this as a function in the first place, except maybe to save space if you plan on doing this over and over.</p>