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?
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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With