[R] NA

John Fox jfox at mcmaster.ca
Fri Apr 18 06:04:04 CEST 2003


Dear William,

At 05:47 PM 4/17/2003 +0200, william ritchie wrote:
>I know this has allready been asked but...
>HOW TO I GET RID OF NA's IN A LIST!!!!

As you say, this question was addressed just a couple of days ago. To 
elaborate on the previous solution, here's a recursive version, with an 
example (the first line of the function given is the non-recursive solution).

 > Lst <- list(a=NULL, b=1, c=list(d=NULL, e=2, f=list(g=3, h=list(i=NULL, 
k=4))))
 > rm.null <- function(L) {
+     L[sapply(L, is.null)] <- NULL
+     for (i in seq(along=L)) if (is.list(L[[i]])) L[[i]] <- Recall(L[[i]])
+     L
+     }
 > rm.null(Lst)
$b
[1] 1

$c
$c$e
[1] 2

$c$f
$c$f$g
[1] 3

$c$f$h
$c$f$h$k
[1] 4

Does that do what you want? Perhaps someone can think of a simpler 
recursive version.

John

-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox



More information about the R-help mailing list