从列表列表中删除 NULL 元素 [英] Remove NULL elements from list of lists

查看:28
本文介绍了从列表列表中删除 NULL 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从列表列表中删除空元素,如下所示,在 R 中:

How do I remove the null elements from a list of lists, like below, in R:

lll <- list(list(NULL),list(1),list("a"))

我想要的对象看起来像:

The object I want would look like:

lll <- list(list(1),list("a"))

我在这里看到了类似的答案:How can I remove列表中的元素?但无法将其从简单列表扩展到列表列表.

I saw a similar answer here: How can I remove an element from a list? but was not able to extend it from simple lists to a list of lists.

编辑

我上面的坏例子.两个答案都适用于更简单的情况(上图).如果列表类似于:

Bad example above on my part. Both answers work on simpler case (above). What if list is like:

lll <- list(list(NULL),list(1,2,3),list("a","b","c"))

获取方式:

lll <- list(list(1,2,3),list("a","b","c"))

推荐答案

这种递归解决方案的优点是可以处理更深层嵌套的列表.

This recursive solution has the virtue of working on even more deeply nested lists.

它密切模仿了 Gabor Grothendieck 对这个非常相似的问题的回答.如果该函数还需要删除诸如 list(NULL)(与 NULL 不同)之类的对象,则需要我修改该代码.

It's closely modeled on Gabor Grothendieck's answer to this quite similar question. My modification of that code is needed if the function is to also remove objects like list(NULL) (not the same as NULL), as you are wanting.

## A helper function that tests whether an object is either NULL _or_ 
## a list of NULLs
is.NullOb <- function(x) is.null(x) | all(sapply(x, is.null))

## Recursively step down into list, removing all such objects 
rmNullObs <- function(x) {
   x <- Filter(Negate(is.NullOb), x)
   lapply(x, function(x) if (is.list(x)) rmNullObs(x) else x)
}

rmNullObs(lll)
# [[1]]
# [[1]][[1]]
# [1] 1
# 
# 
# [[2]]
# [[2]][[1]]
# [1] "a"

这是一个将其应用于更深层嵌套列表的示例,目前其他提出的解决方案在该列表上都失败了.

Here is an example of its application to a more deeply nested list, on which the other currently proposed solutions variously fail.

LLLL <- list(lll)
rmNullObs(LLLL)
# [[1]]
# [[1]][[1]]
# [[1]][[1]][[1]]
# [[1]][[1]][[1]][[1]]
# [1] 1
# 
# 
# [[1]][[1]][[2]]
# [[1]][[1]][[2]][[1]]
# [1] "a"

这篇关于从列表列表中删除 NULL 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆