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

查看:86
本文介绍了从列表列表中删除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"))

我在这里看到了类似的答案:如何删除列表中的元素?,但是无法将其从简单列表扩展到列表列表.

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天全站免登陆