Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract non null elements from a list in R

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.

like image 240
qed Avatar asked Jun 03 '13 12:06

qed


People also ask

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.

IS NOT NULL in R?

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.

IS NULL For list in R?

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.

How do I remove null rows in R?

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


2 Answers

Here's another option:

Filter(Negate(is.null), x) 
like image 195
Matthew Plourde Avatar answered Sep 19 '22 03:09

Matthew Plourde


What about:

x[!unlist(lapply(x, is.null))] 

Here is a brief description of what is going on.

  1. lapply tells us which elements are NULL

    R> lapply(x, is.null) $a [1] FALSE  $b [1] FALSE  $c [1] TRUE 
  2. Next we convect the list into a vector:

    R> unlist(lapply(x, is.null))  a     b     c  FALSE FALSE  TRUE  
  3. Then we switch TRUE to FALSE:

    R> !unlist(lapply(x, is.null))     a     b     c  TRUE  TRUE FALSE  
  4. Finally, we select the elements using the usual notation:

    x[!unlist(lapply(x, is.null))] 
like image 32
csgillespie Avatar answered Sep 22 '22 03:09

csgillespie