Remove empty elements from list with character(0)

2020-02-07 19:57发布

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 list
5条回答
干净又极端
2楼-- · 2020-02-07 20:04

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
查看更多
男人必须洒脱
3楼-- · 2020-02-07 20:08

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 != ""]
查看更多
够拽才男人
4楼-- · 2020-02-07 20:10

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"
#> 
查看更多
孤傲高冷的网名
5楼-- · 2020-02-07 20:13

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
查看更多
小情绪 Triste *
6楼-- · 2020-02-07 20:17

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"
查看更多
登录 后发表回答