title: Apply function across subset of columns in data.table with .SDcols
body: <p>I want to apply a function over a subset of variables in a data.table.   In this case I'm simply changing variable types.  I can do this a few different ways in data.table, however I'm looking for a way that does not require an intermediate assignment (<code>mycols</code> in this example) and does not require me to specify the columns I want to change twice.   Here is a simplified reproducible example:</p>
  
  <pre><code>library('data.table')
  n&lt;-30
  dt &lt;- data.table(a=sample(1:5, n, replace=T),
         b=as.character(sample(seq(as.Date('2011-01-01'), as.Date('2015-01-01'), length.out=n))),
         c1235=as.character(sample(seq(as.Date('2012-01-01'), as.Date('2013-01-01'), length.out=n))),
         d7777=as.character(sample(seq(as.Date('2012-01-01'), as.Date('2013-01-01'), length.out=n)))
  )
  </code></pre>
  
  <p><strong>WAY 1:</strong> this works... but it's hard-coded</p>
  
  <pre><code>mycols &lt;- c('b', 'c1235', 'd7777')
  dt1 &lt;- dt[,(mycols):=lapply(.SD, as.Date), .SDcols=mycols]
  </code></pre>
  
  <p><strong>WAY 2:</strong> this works... but I need to crate an intermediate object for it to work (<code>mycols</code>)</p>
  
  <pre><code>mycols &lt;- which(sapply(dt, class)=='character')
  dt2 &lt;- dt[,(mycols):=lapply(.SD, as.Date), .SDcols=mycols]
  </code></pre>
  
  <p><strong>WAY 3:</strong> this works, but I need to specify this long expression twice </p>
  
  <pre><code>dt3 &lt;- dt[,(which(sapply(dt, class)=='character')):=lapply(.SD, as.Date), .SDcols=which(sapply(dt, class)=='character')]
  </code></pre>
  
  <p><strong>WAY 4:</strong> this doesn't work, but I want something like this that allows me to only specify the variables that make <code>.SDcols</code> once.  I'm looking for some way to replace <code>(.SD):=</code> with something that works... or chain things together.  Really I'd be curious to see if anyone has a method for performing what is done in WAY 1,2,3 without specifying an intermediate assignment that bloats the environment and does not require specifying the same columns twice. </p>
  
  <pre><code>dt3 &lt;- dt[,(.SD):=lapply(.SD, as.Date), .SDcols=which(sapply(dt, class)=='character')]
  </code></pre>