title: Why does lapply() not retain my data.table keys?
body: <p>I have a bunch of data.tables in a list. I want to apply <code>unique()</code> to each data.table in my list, but doing so destroys all my data.table keys.</p>
  
  <p>Here's an example:</p>
  
  <pre><code>A &lt;- data.table(a = rep(c("a","b"), each = 3), b = runif(6), key = "a")
  B &lt;- data.table(x = runif(6), b = runif(6), key = "x")
  
  blah &lt;- unique(A)
  </code></pre>
  
  <p>Here, <code>blah</code> still has a key, and everything is right in the world:</p>
  
  <pre><code>key(blah)
  
  # [1] "a"
  </code></pre>
  
  <p>But if I add the data.tables to a list and use <code>lapply()</code>, the keys get destroyed:</p>
  
  <pre><code>dt.list &lt;- list(A, B)
  
  unique.list &lt;- lapply(dt.list, unique) # Keys destroyed here
  
  lapply(unique.list, key) 
  
  # [[1]]
  # NULL
  
  # [[2]]
  # NULL
  </code></pre>
  
  <p>This probably has to do with me not really understanding what it means for keys to be assigned "by reference," as I've had other problems with keys disappearing.</p>
  
  <p>So:</p>
  
  <ul>
  <li><strong>Why does lapply not retain my keys?</strong></li>
  <li>What does it mean to say keys are assigned "by reference"?</li>
  <li>Should I even  be storing data.tables in a list?</li>
  <li>How can I safely store/manipulate data.tables without fear of losing my keys?</li>
  </ul>
  
  <p><strong>EDIT:</strong></p>
  
  <p>For what it's worth, the dreaded <code>for</code> loop works just fine, too:</p>
  
  <pre><code>unique.list &lt;- list()
  
  for (i in 1:length(dt.list)) {
    unique.list[[i]] &lt;- unique(dt.list[[i]])
  }
  
  lapply(unique.list, key)
  
  # [[1]]
  # [1] "a"
  
  # [[2]]
  # [1] "x"
  </code></pre>
  
  <p>But this is R, and <code>for</code> loops are <em>evil</em>.</p>