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
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.
Using List. To remove all null occurrences from the list, we can continuously call remove(null) until all null values are removed. Please note that the list will remain unchanged if it does not contain any null value.
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.
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).
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