Update multiple data.table columns elegantly
<p>I'm trying to do a simple thing, divide 40 columns of a data.table by their mean. I cannot provide the actual data (not all columns are numeric, and I have > 8M rows), but here's an example:</p>

<pre><code>library(data.table)   

dt &lt;- data.table(matrix(sample(1:100,4000,T),ncol=40))
colmeans &lt;- colMeans(dt)
</code></pre>

<p>Next I thought I would do:</p>

<pre><code>for (col in names(colmeans)) dt[,col:=dt[,col]/colmeans[col]]   
</code></pre>

<p>But this returns an error since <code>dt[,col]</code> require that column names are not quoted. Using <code>as.name(col)</code> doesn't cut it.
Now,</p>

<pre><code>res &lt;- t(t(dt[,1:40,with=F]/colmeans))
</code></pre>

<p>contains the expeded result, but I cannot insert it back in the data.table, as</p>

<pre><code>dt[,1:40] &lt;- res
</code></pre>

<p>does not work, neither does <code>dt[,1:40:=res, with=F]</code>. </p>

<p>The following works, but I find it quite ugly:</p>

<pre><code>for (i in seq_along(colmeans)) dt[,i:=dt[,i,with=F]/colmeans[i],with=F]
</code></pre>

<p>Sure, I could also recreate an new data.table by calling <code>data.table()</code> on <code>res</code> and the other non-numerical columns my data.table has, but isn't their anything more efficient?</p>