R: removing NULL elements from a list

There's a function that automatically removes all the null entries of a list, and if the list is named, it maintains the names of the non-null entries.

This function is called compact from the package plyr.

l <- list( NULL, NULL, foo, bar)
names(l) <- c( "one", "two", "three", "four" )

plyr::compact(l)

If you want to preserve the indexes of the non-null entries, you can name the list as it is done in the post before and then compact your list:

names(l) <- seq_along(l)
plyr::compact(l)

The closest you'll be able to get is to first name the list elements and then remove the NULLs.

names(x) <- seq_along(x)

## Using some higher-order convenience functions
Filter(Negate(is.null), x)
# $`11`
# [1] 123
# 
# $`13`
# [1] 456

# Or, using a slightly more standard R idiom
x[sapply(x, is.null)] <- NULL
x
# $`11`
# [1] 123
# 
# $`13`
# [1] 456

Simply use mylist[lengths(mylist) != 0].

Function lengths() was introduced in R 3.2.0 (April 2015).


The purrr package, included in Tidyverse, has elegant and fast functions for working with lists:

require(tidyverse)

# this works
compact(mylist)

# or this
mylist %>% discard(is.null)

# or this
# pipe "my_list" data object into function "keep()", make lambda function inside "keep()" to return TRUE FALSE.
mylist %>% keep( ~ !is.null(.) )

All above options are from Purrr. Output is:

[[1]] 
[1] 123

[[2]] 
[1] 456

Note: compact() was in plyr, but dplyr superseded plyr, and compact() stayed around but moved to purrr. Anyway, all the functions are within the parent package tidyverse.



Here's a link to the Purrr cheat sheet download:

https://rstudio.com/resources/cheatsheets/

Or to view the Purrr cheatsheet directly in a browser:

https://evoldyn.gitlab.io/evomics-2018/ref-sheets/R_purrr.pdf

Tags:

R