title: Create a function to loop through data table variables and add counts
body: <p>I would like to create a function that inserts new column in a data table with the counts for each variable in the list given as parameter.</p>
  
  <p>Here is a working code, but it is not a function:</p>
  
  <pre><code>a = data.table(x=c(1,2,3,3,1), y=c(3,4,4,23,3))
  setkey(a, "x", "y")
  a[,x_cnt := .N, by=list(x)]
  a[,y_cnt := .N, by=list(y)]
  &gt; a
     x  y x_cnt y_cnt
  1: 1  3     2     2
  2: 1  3     2     2
  3: 2  4     1     2
  4: 3  4     2     2
  5: 3 23     2     1
  </code></pre>
  
  <p>Here is my code so far:</p>
  
  <pre><code>a = data.table(x=c(1,2,3,3,1), y=c(3,4,4,23,3))
  my.f1cnt &lt;- function(ds, variable_list)
  {
      for(var in variable_list)
      {
          setkey(ds, var)
          ds[,paste0(var, "_cnt") := .N, by=list(var)]
      }
      #return
      ds
  }
  
  my.f1cnt(a, c("x","y"))
  Error in setkeyv(x, cols, verbose = verbose) : 
    some columns are not in the data.table: var
  </code></pre>