Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: removing NULL elements from a list

Tags:

r

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 
like image 497
Adrian Avatar asked Oct 07 '15 23:10

Adrian


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.

Can we remove null from list?

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.

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.


2 Answers

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 
like image 132
Josh O'Brien Avatar answered Oct 04 '22 13:10

Josh O'Brien


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

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

like image 40
F. Privé Avatar answered Oct 04 '22 13:10

F. Privé