且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从列表列表中删除 NULL 元素

更新时间:2022-05-27 22:05:15

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

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"