Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove NULL elements from list of lists

Tags:

list

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.

EDIT

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"))

How to get:

lll <- list(list(1,2,3),list("a","b","c"))
like image 933
Chris Avatar asked Oct 23 '14 23:10

Chris


People also ask

Can we remove null from list?

Using List. To remove all null occurrences from the list, we can continuously call remove(null) until all null values are removed. Please note that the list will remain unchanged if it does not contain any null value.

How do you remove null elements from a list in Python?

The easiest way to remove none from list in Python is by using the list filter() method. The list filter() method takes two parameters as function and iterator. To remove none values from the list we provide none as the function to filter() method and the list which contains none values.

How do I remove null elements from a list in R?

If a list contains NULL then we might want to replace it with another value or remove it from the list if we do not have any replacement for it. To remove the NULL value from a list, we can use the negation of sapply with is. NULL.


2 Answers

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

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"
like image 152
Josh O'Brien Avatar answered Oct 20 '22 03:10

Josh O'Brien


Here's an option using Filter and Negate combination

Filter(Negate(function(x) is.null(unlist(x))), lll)
# [[1]]
# [[1]][[1]]
# [1] 1
#
#
# [[2]]
# [[2]][[1]]
# [1] "a"
like image 21
David Arenburg Avatar answered Oct 20 '22 01:10

David Arenburg