title: Apply a function to specified columns in a data.table and extract group
body: <p>I am curious if I can do a similar thing as this question <a href="https://stackoverflow.com/questions/16846380/apply-a-function-to-every-specified-column-in-a-data-table-and-update-by-referen">Apply a function to every specified column in a data.table and update by reference</a> but creating new columns based off a group.</p>
  <p>This is my code for example (very rudimentary code)</p>
  <pre><code>dt &lt;- data.table(a = 1:4, b = 1:4, d = c(&quot;Hi&quot;, &quot;Hello&quot;, &quot;Please&quot;, &quot;Hi&quot;))
  
  cols &lt;- c(&quot;a&quot;, &quot;b&quot;)
  out_cols = paste(&quot;Percentile Rank 1&quot;, cols, sep = &quot; &quot;)
  have.fun3[, c(out_cols) := lapply(.SD,  percent.rank.V2), .SDcols = cols]
  </code></pre>
  <p>Where I am calculating the Percentile rank of of columns a and b. My code it is setup to create two new columns called &quot;Percentile Rank 1 a&quot; and &quot;Percentile Rank 1 b&quot;. However, what I would like to do is calculate the percentile rank by group and then create columns based off those groups.</p>
  <p>So I would create 4 new columns called &quot;Percentile Rank 1 a Hi&quot; ... &quot;Percentile Rank 2 a Hello&quot; ... &quot;Percentile Rank 2 b Please&quot;</p>
  <pre><code>cols &lt;- c(&quot;a&quot;, &quot;b&quot;)
  out_cols = paste(&quot;Percentile Rank 1&quot;, cols, sep = &quot; &quot;)
  have.fun3[, c(out_cols) := lapply(.SD,  percent.rank.V2), .SDcols = cols, by = d]
  </code></pre>
  <p>but it doesn't do what I would like (it only outputs the Percentile Ranks for the Hi group).</p>