Remove empty elements from list with character(0)

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

list2
# $`hsa:7476`
# [1] "1","2","3"
# 
# $`hsa:656`
# character(0)
#
# $`hsa:7475`
# character(0)
#
# $`hsa:7472`
# character(0)

I don't know how to deal with them. I mean if NULL it is much simpler. How can I remove these elements such that just hsa:7476 remains in the list.


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"

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

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

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"
#>