Consider the following list:
> l1 <- list(NULL,1,2,list(NULL,3,list(NULL,4))) > str(l1) List of 4 $ : NULL $ : num 1 $ : num 2 $ :List of 3 ..
This can be done recursively:
rmNull <- function(x) { x <- Filter(Negate(is.null), x) lapply(x, function(x) if (is.list(x)) rmNull(x) else x) } l2 <- rmNull(l1)
giving:
> str(l2) List of 3 $ : num 1 $ : num 2 $ :List of 2 ..$ : num 3 ..$ :List of 1 .. ..$ : num 4