Remove empty elements from list with character(0)

后端 未结 5 1869
渐次进展
渐次进展 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 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 != ""]
    

提交回复
热议问题