Extract non null elements from a list in R

后端 未结 4 641
别跟我提以往
别跟我提以往 2020-12-08 19:59

I have a list like this:

    x = list(a = 1:4, b = 3:10, c = NULL)
    x
    #$a
    #[1] 1 2 3 4
    #
    #$b
    #[1]  3  4  5  6  7  8  9 10
    #
    #$         


        
4条回答
  •  清歌不尽
    2020-12-08 20:18

    What about:

    x[!unlist(lapply(x, is.null))]
    

    Here is a brief description of what is going on.

    1. lapply tells us which elements are NULL

      R> lapply(x, is.null)
      $a
      [1] FALSE
      
      $b
      [1] FALSE
      
      $c
      [1] TRUE
      
    2. Next we convect the list into a vector:

      R> unlist(lapply(x, is.null)) 
      a     b     c 
      FALSE FALSE  TRUE 
      
    3. Then we switch TRUE to FALSE:

      R> !unlist(lapply(x, is.null))
          a     b     c 
      TRUE  TRUE FALSE 
      
    4. Finally, we select the elements using the usual notation:

      x[!unlist(lapply(x, is.null))]
      

提交回复
热议问题