Extract non null elements from a list in R

后端 未结 4 617
别跟我提以往
别跟我提以往 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条回答
  •  Happy的楠姐
    2020-12-08 20:23

    Simpler and likely quicker than the above, the following works for lists of any non-recursive (in the sense of is.recursive) values:

    example_1_LST <- list(NULL, a=1.0, b=Matrix::Matrix(), c=NULL, d=4L)
    example_2_LST <- as.list(unlist(example_1_LST, recursive=FALSE))
    

    str(example_2_LST) prints:

    List of 3
     $ a: num 1
     $ b:Formal class 'lsyMatrix' [package "Matrix"] with 5 slots
      .. ..@ x       : logi NA
      .. ..@ Dim     : int [1:2] 1 1
      .. ..@ Dimnames:List of 2
      .. .. ..$ : NULL
      .. .. ..$ : NULL
      .. ..@ uplo    : chr "U"
      .. ..@ factors : list()
     $ d: int 4
    

提交回复
热议问题