2013-06-03 43 views
19

我有一个这样的名单:提取非空元素中的R

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 

,我想提取不为空的所有元素。如何才能做到这一点?谢谢。

回答

28

这里的另一种选择:

Filter(Negate(is.null), x) 
11

什么:

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

这里是正在发生的事情的简要说明。

  1. lapply告诉我们哪些元素是NULL

    R> lapply(x, is.null) 
    $a 
    [1] FALSE 
    
    $b 
    [1] FALSE 
    
    $c 
    [1] TRUE 
    
  2. 接下来我们对流列表为载体:

    R> unlist(lapply(x, is.null)) 
    a  b  c 
    FALSE FALSE TRUE 
    
  3. 然后我们切换TRUEFALSE

    R> !unlist(lapply(x, is.null)) 
        a  b  c 
    TRUE TRUE FALSE 
    
  4. 最后,我们选择使用普通的符号元素:

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

'x [!sapply(x,is.null)]'会更快吗? – Julius

0

简单且可能比上面的快,对于列出了以下工作任何非递归(在is.recursive的意义上)值:

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)打印:

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

你不需要用'base ::'和'utils ::'来引用base和utils中的函数。 –

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

这可以推广到对列表中的任何逻辑语句,只需在逻辑子为 “is.null”。