[R] removing NULL elements from a list

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Apr 14 17:06:58 CEST 2003


somelist[!sapply(somelist, is.null)]

e.g. 

> s <- list(a=1, b=NULL, c=3, d=NULL, e=5)
> s[!sapply(s, is.null)]
$a
[1] 1

$c
[1] 3

$e
[1] 5

It you want to confuse people, try s[sapply(s, is.null)] <- NULL
which also removes the NULL components.

On Mon, 14 Apr 2003, Ramon Diaz wrote:

> I have a list, where several components are NULL, and I'd like to obtain
> that very same list without the NULL components (i.e., I do not want to
> unlist or otherwise loose the rest of the list structure). I can do that
> with a loop, but how could I do it without a loop?

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list