I have a list like this:
x = list(a = 1:4, b = 3:10, c = NULL) x #$a #[1] 1 2 3 4 # #$b #[1] 3 4 5 6 7 8 9 10 # #$c #NULL
and I want to extract all elements that are not null. How can this be done? Thanks.
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.
Basic R Syntax: The R function is. null indicates whether a data object is of the data type NULL (i.e. a missing value). The function returns TRUE in case of a NULL object and FALSE in case that the data object is not NULL.
Description. NULL represents the null object in R. NULL is used mainly to represent the lists with zero length, and is often returned by expressions and functions whose value is undefined.
To remove all rows having NA, we can use na. omit function. For Example, if we have a data frame called df that contains some NA values then we can remove all rows that contains at least one NA by using the command na. omit(df).
Here's another option:
Filter(Negate(is.null), x)
What about:
x[!unlist(lapply(x, is.null))]
Here is a brief description of what is going on.
lapply
tells us which elements are NULL
R> lapply(x, is.null) $a [1] FALSE $b [1] FALSE $c [1] TRUE
Next we convect the list into a vector:
R> unlist(lapply(x, is.null)) a b c FALSE FALSE TRUE
Then we switch TRUE
to FALSE
:
R> !unlist(lapply(x, is.null)) a b c TRUE TRUE FALSE
Finally, we select the elements using the usual notation:
x[!unlist(lapply(x, is.null))]
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