Remove empty elements from list with character(0)

RList

R Problem Overview


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.

R Solutions


Solution 1 - R

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"

Solution 2 - R

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

Solution 3 - R

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

Solution 4 - R

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 != ""]

Solution 5 - R

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichard A. Sch&#228;ferView Question on Stackoverflow
Solution 1 - RagstudyView Answer on Stackoverflow
Solution 2 - RJulius VainoraView Answer on Stackoverflow
Solution 3 - RlukeAView Answer on Stackoverflow
Solution 4 - Rnot2qubitView Answer on Stackoverflow
Solution 5 - RArtem KlevtsovView Answer on Stackoverflow