Remove empty elements from list with character(0)

后端 未结 5 1862
渐次进展
渐次进展 2020-12-13 08:33

How can I remove empty elements from a list that contain zero length pairlist as character(0), integer(0) etc...

list2
# $`hsa:7476         


        
相关标签:
5条回答
  • 2020-12-13 08:54

    For the sake of completeness, the purrr package from the popular tidyverse has some useful functions for working with lists - compact (introduction) does the trick, too, and works fine with magrittr's %>% pipes:

    l <- list(1:3, "foo", character(0), integer(0))
    library(purrr)
    compact(l)
    # [[1]]
    # [1] 1 2 3
    #
    # [[2]]
    # [1] "foo"
    

    or

    list(1:3, "foo", character(0), integer(0)) %>% compact
    
    0 讨论(0)
  • 2020-12-13 09:00

    One possible approach is

    Filter(length, l)
    # [[1]]
    # [1] 1 2 3
    # 
    # [[2]]
    # [1] "foo"
    

    where

    l <- list(1:3, "foo", character(0), integer(0))
    

    This works due to the fact that positive integers get coerced to TRUE by Filter and, hence, are kept, while zero doesn't:

    as.logical(0:2)
    # [1] FALSE  TRUE  TRUE
    
    0 讨论(0)
  • 2020-12-13 09:07

    Another option(I think more efficient) by keeping index where element length > 0 :

    l[lapply(l,length)>0] ## you can use sapply,rapply
    
    [[1]]
    [1] 1 2 3
    
    [[2]]
    [1] "foo"
    
    0 讨论(0)
  • 2020-12-13 09:13

    Use lengths() to define lengths of the list elements:

    l <- list(1:3, "foo", character(0), integer(0))
    l[lengths(l) > 0L]
    #> [[1]]
    #> [1] 1 2 3
    #> 
    #> [[2]]
    #> [1] "foo"
    #> 
    
    0 讨论(0)
  • 2020-12-13 09:16

    Funny enough, none of the many solutions above remove the empty/blank character string: "". But the trivial solution is not easily found: L[L != ""].

    To summarize, here are some various ways to remove unwanted items from an array list.

    # Our Example List:
    L <- list(1:3, "foo", "", character(0), integer(0))
    
    # 1. Using the *purrr* package:
    library(purrr)
    compact(L)
    
    # 2. Using the *Filter* function:
    Filter(length, L)
    
    # 3. Using *lengths* in a sub-array specification:
    L[lengths(L) > 0]
    
    # 4. Using *lapply* (with *length*) in a sub-array specification:
    L[lapply(L,length)>0]
    
    # 5. Using a sub-array specification:
    L[L != ""]
    
    # 6. Combine (3) & (5)
    L[lengths(L) > 0 & L != ""]
    
    0 讨论(0)
提交回复
热议问题