Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently remove all NULL values in a list and all sublists

Tags:

list

null

r

Consider the following list:

> l1 <- list(NULL,1,2,list(NULL,3,list(NULL,4)))
> str(l1)
List of 4
 $ : NULL
 $ : num 1
 $ : num 2
 $ :List of 3
  ..$ : NULL
  ..$ : num 3
  ..$ :List of 2
  .. ..$ : NULL
  .. ..$ : num 4

To remove NULL values from the first level, simply call

l1[vapply(l1,is.null,logical(1L))] <- NULL

Now I want to remove all NULL values at all levels, I come up with the following code.

list.clean <- function(.data, fun = is.null, recursive = FALSE) {
  if(recursive) {
    .data <- lapply(.data, function(.item) {
      if(is.list(.item)) list.clean(.item, fun, TRUE)
      else .item
    })
  }
  .data[vapply(.data,fun,logical(1L))] <- NULL
  .data
}

And calling

> list.clean(l1, recursive = TRUE)
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[[3]][[1]]
[1] 3

[[3]][[2]]
[[3]][[2]][[1]]
[1] 4

Although it works right now, is there a better or faster way to do so?

like image 349
Kun Ren Avatar asked Aug 01 '14 13:08

Kun Ren


People also ask

How do you remove nulls from a list?

Get the list with null values. Repeatedly call remove(null) on the list, until all null values are removed. Return/Print the list (now with all null values removed).

How do you remove null from a list in Python?

There are a several ways to remove null value from list in python. we will use filter(), join() and remove() functions to delete empty string from list.

How do I remove null values in Salesforce?

with Set there is an option to remove the null directly instea with index position. setOfRecords. remove(null) will remove all null records from the set.


1 Answers

This can be done recursively:

rmNull <- function(x) {
   x <- Filter(Negate(is.null), x)
   lapply(x, function(x) if (is.list(x)) rmNull(x) else x)
}
l2 <- rmNull(l1)

giving:

> str(l2)
List of 3
 $ : num 1
 $ : num 2
 $ :List of 2
  ..$ : num 3
  ..$ :List of 1
  .. ..$ : num 4
like image 54
G. Grothendieck Avatar answered Sep 30 '22 05:09

G. Grothendieck