Extract non null elements from a list in R

此生再无相见时 提交于 2019-11-27 05:42:49

问题


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
    #
    #$c
    #NULL

and I want to extract all elements that are not null. How can this be done? Thanks.


回答1:


Here's another option:

Filter(Negate(is.null), x)



回答2:


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))]
    



回答3:


x[!sapply(x,is.null)]

This generalizes to any logical statement about the list, just sub in the logic for "is.null".




回答4:


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


来源:https://stackoverflow.com/questions/16896376/extract-non-null-elements-from-a-list-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!