R:从列表中删除NULL元素

时间:2015-10-07 23:42:11

标签: r

mylist <- list(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
    123, NULL, 456)

> mylist
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

[[5]]
NULL

[[6]]
NULL

[[7]]
NULL

[[8]]
NULL

[[9]]
NULL

[[10]]
NULL

[[11]]
[1] 123

[[12]]
NULL

[[13]]
[1] 456

我的列表有13个元素,其中11个为NULL。我想删除它们,但保留非空元素的索引。

mylist2 = mylist[-which(sapply(mylist, is.null))]
> mylist2
[[1]]
[1] 123

[[2]]
[1] 456

这样就删除了NULL元素,但是我不希望非空元素被重新索引,即我希望mylist2看起来像这样,其中非空条目的索引被保留。< / p>

> mylist2
[[11]]
[1] 123

[[13]]
[1] 456

8 个答案:

答案 0 :(得分:56)

您最接近的是首先命名列表元素,然后删除NULL。

names(x) <- seq_along(x)

## Using some higher-order convenience functions
Filter(Negate(is.null), x)
# $`11`
# [1] 123
# 
# $`13`
# [1] 456

# Or, using a slightly more standard R idiom
x[sapply(x, is.null)] <- NULL
x
# $`11`
# [1] 123
# 
# $`13`
# [1] 456

答案 1 :(得分:17)

有一个函数可以自动删除列表的所有空条目,如果列表被命名,它会维护非空条目的名称。

此功能从包compact中调用plyr

l <- list( NULL, NULL, foo, bar)
names(l) <- c( "one", "two", "three", "four" )

plyr::compact(l)

如果要保留非空条目的索引,可以按照之前的帖子命名列表,然后压缩列表:

names(l) <- seq_along(l)
plyr::compact(l)

答案 2 :(得分:5)

如果你想保留你可以做的名字

a <- list(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
          123, NULL, 456)
non_null_names <- which(!sapply(a, is.null))
a <- a[non_null_names]
names(a) <- non_null_names
a

然后,您可以访问这样的元素

a[['11']]
num <- 11
a[[as.character(num)]]
a[[as.character(11)]]
a$`11`

但是,您无法使用整齐的[[11]][[13]]表示法,因为这些表示数字索引。

答案 3 :(得分:5)

只需执行mylist[lengths(mylist) != 0]

答案 4 :(得分:4)

这里有方便的链接符号

library(magrittr)

mylist %>%
  setNames(seq_along(.)) %>%
  Filter(. %>% is.null %>% `!`, .)

答案 5 :(得分:3)

Tidyverse 中包含的 purrr 软件包具有用于处理列表的优雅且快速的功能:

require(tidyverse)

# this works
compact(mylist)

# or this
mylist %>% discard(is.null)

# or this
# pipe "my_list" data object into function "keep()", make lambda function inside "keep()" to return TRUE FALSE.
mylist %>% keep( ~ !is.null(.) )

以上所有选项均来自Purrr。输出为:

[[1]] 
[1] 123

[[2]] 
[1] 456

注意:compact()在plyr中,但是dplyr取代了plyr,compact()停留在附近但移至purrr。无论如何,所有功能都在父包tidyverse中。



这是Purrr备忘单下载的链接:

https://rstudio.com/resources/cheatsheets/

或者直接在浏览器中查看Purrr备忘单:

https://evoldyn.gitlab.io/evomics-2018/ref-sheets/R_purrr.pdf

答案 6 :(得分:1)

这是仅使用基本R函数的一种非常简单的方法:

names(mylist) <- 1:length(mylist)
mylist2 <- mylist[which(!sapply(mylist, is.null))]

答案 7 :(得分:0)

此解决方案也适用于嵌套列表

rlist::list.clean(myNestedlist ,recursive = T)
相关问题