title: Weighted sum of variables by groups with data.table
body: <p>I am looking for a solution to compute weighted sum of some variables by groups with data.table. I hope the example is clear enough.</p>
  
  <pre><code>require(data.table)
  
  dt &lt;- data.table(matrix(1:200, nrow = 10))
  dt[, gr := c(rep(1,5), rep(2,5))]
  dt[, w := 2]
  
  # Error: object 'w' not found
  dt[, lapply(.SD, function(x) sum(x * w)),
     .SDcols = paste0("V", 1:4)]
  
  # Error: object 'w' not found
  dt[, lapply(.SD * w, sum),
     .SDcols = paste0("V", 1:4)]
  
  # This works with out groups
  dt[, lapply(.SD, function(x) sum(x * dt$w)),
     .SDcols = paste0("V", 1:4)]
  
  # It does not work by groups
  dt[, lapply(.SD, function(x) sum(x * dt$w)),
     .SDcols = paste0("V", 1:4), keyby = gr]
  
  # The result to be expected
  dt[, list(V1 = sum(V1 * w),
            V2 = sum(V2 * w),
            V3 = sum(V3 * w),
            V4 = sum(V4 * w)), keyby = gr]
  
  ### from Aruns answer
  dt[, lapply(.SD[, paste0("V", 1:4), with = F],
              function(x) sum(x*w)), by=gr]
  </code></pre>