mylist <- list(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
123, NULL, 456)
> mylist
[[1]]
NULL
[[2]]
NULL
[[3]]
NULL
[[4]]
NULL
[[5]]
NULL
[[6]]
NULL
[[7]]
NULL
[[8]]
NULL
[[9]]
NULL
[[10]]
NULL
[[11]]
[1] 123
[[12]]
NULL
[[13]]
[1] 456
My list has 13 elements, 11 of which are NULL. I would like to remove them, but preserve the indices of the elements that are nonempty.
mylist2 = mylist[-which(sapply(mylist, is.null))]
> mylist2
[[1]]
[1] 123
[[2]]
[1] 456
This removes the NULL elements just fine, but I don't want the nonempty elements to be reindexed, i.e, I want mylist2
to look something like this, where the indices of the nonempty entries are preserved.
> mylist2
[[11]]
[1] 123
[[13]]
[1] 456
The closest you'll be able to get is to first name the list elements and then remove the NULLs.
Simply do
mylist[lengths(mylist) != 0]
.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 packageplyr
.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:
The
purrr
package, included in Tidyverse, has elegant and fast functions for working with lists:All above options are from Purrr. Output is:
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
Here it is with convenient chaining notation
This solution works with nested list as well