title: R: removing NULL elements from a list
body: <pre><code>mylist &lt;- list(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
      123, NULL, 456)
  
  &gt; mylist
  [[1]]
  NULL
  
  [[2]]
  NULL
  
  [[3]]
  NULL
  
  [[4]]
  NULL
  
  [[5]]
  NULL
  
  [[6]]
  NULL
  
  [[7]]
  NULL
  
  [[8]]
  NULL
  
  [[9]]
  NULL
  
  [[10]]
  NULL
  
  [[11]]
  [1] 123
  
  [[12]]
  NULL
  
  [[13]]
  [1] 456
  </code></pre>
  
  <p>My list has 13 elements, 11 of which are NULL. I would like to remove them, but preserve the indices of the elements that are nonempty. </p>
  
  <pre><code>mylist2 = mylist[-which(sapply(mylist, is.null))]
  &gt; mylist2
  [[1]]
  [1] 123
  
  [[2]]
  [1] 456
  </code></pre>
  
  <p>This removes the NULL elements just fine, but I don't want the nonempty elements to be reindexed, i.e, I want <code>mylist2</code> to look something like this, where the indices of the nonempty entries are preserved.</p>
  
  <pre><code>&gt; mylist2
  [[11]]
  [1] 123
  
  [[13]]
  [1] 456
  </code></pre>