R语言 从列表中删除NULL元素[重复]

mxg2im7a  于 2023-05-26  发布在  其他
关注(0)|答案(8)|浏览(226)

此问题已在此处有答案

Extract non null elements from a list(5个答案)
3天前关闭。

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看起来像这样,其中非空条目的索引被保留。

> mylist2
[[11]]
[1] 123

[[13]]
[1] 456
xoefb8l8

xoefb8l81#

最接近的方法是首先命名列表元素,然后删除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
mlmc2os5

mlmc2os52#

只需使用mylist[lengths(mylist) != 0]即可。

函数lengths()在R 3.2.0(2015年4月)中引入。

vuktfyat

vuktfyat3#

  • *purrr包包含在Tidyverse**中,提供优雅而快速的列表处理功能:
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

r6l8ljro

r6l8ljro4#

有一个函数可以自动删除列表中的所有空条目,如果列表被命名,它会维护非空条目的名称。
这个函数在plyr软件包中被称为compact

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

plyr::compact(l)

如果你想保留非空条目的索引,你可以像在之前的文章中那样命名列表,然后压缩列表:

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

falq053o5#

如果你想保留你的名字

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]]表示法来得到它们,因为它们表示的是数字索引。

wfveoks0

wfveoks06#

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

rlist::list.clean(myNestedlist ,recursive = T)
yuvru6vn

yuvru6vn7#

这里是方便的链接符号

library(magrittr)

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

jgwigjjp8#

这里有一个非常简单方法,只使用基本的R函数:

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

相关问题