title: Efficiently remove all NULL values in a list and all sublists
body: <p>Consider the following list:</p>
  
  <pre><code>&gt; l1 &lt;- list(NULL,1,2,list(NULL,3,list(NULL,4)))
  &gt; str(l1)
  List of 4
   $ : NULL
   $ : num 1
   $ : num 2
   $ :List of 3
    ..$ : NULL
    ..$ : num 3
    ..$ :List of 2
    .. ..$ : NULL
    .. ..$ : num 4
  </code></pre>
  
  <p>To remove <code>NULL</code> values from the first level, simply call</p>
  
  <pre><code>l1[vapply(l1,is.null,logical(1L))] &lt;- NULL
  </code></pre>
  
  <p>Now I want to remove all <code>NULL</code> values at all levels, I come up with the following code.</p>
  
  <pre><code>list.clean &lt;- function(.data, fun = is.null, recursive = FALSE) {
    if(recursive) {
      .data &lt;- lapply(.data, function(.item) {
        if(is.list(.item)) list.clean(.item, fun, TRUE)
        else .item
      })
    }
    .data[vapply(.data,fun,logical(1L))] &lt;- NULL
    .data
  }
  </code></pre>
  
  <p>And calling</p>
  
  <pre><code>&gt; list.clean(l1, recursive = TRUE)
  [[1]]
  [1] 1
  
  [[2]]
  [1] 2
  
  [[3]]
  [[3]][[1]]
  [1] 3
  
  [[3]][[2]]
  [[3]][[2]][[1]]
  [1] 4
  </code></pre>
  
  <p>Although it works right now, is there a better or faster way to do so?</p>