lapply() when function returns NULL

two options come to mind:

Either

trash_can <- lapply(a.list, x)

or

invisible(lapply(a.list, x))

The first one makes me wonder if there is an analog of Linux's /dev/null in R that you can use to redirect stuff that you don't want. The only problem with creating the variable trash_can is that it will hang around and use up memory unless you rm(trash_can). But I don't think that's a problem here.


You could just do

a.list <- a.list[!sapply(a.list, is.null)]

You did

R> x <- function(x) { return(NULL) }
R> a.list <- list(a=1,b=2,c=3)
R> res <- lapply(a.list, x)
R> res
$a
NULL

$b
NULL

$c
NULL

R>

and as as you asked lapply to sweep over all elements of the list, you can hardly complain you get results (in res) for all elements of a.list. That is correct.

But what nice about the NULL values, though, is that it is trivial to have them skipped in the next aggregation step:

R> do.call(rbind, res)
NULL
R> 

So I've mostly used this approach of returning NULL when the data had an issue or another irregularity arose, as you can easily aggregate the 'good' results afterwards.


I think you might want to take a look at l_ply from the plyr package. It is supposed to return nothing, and it has all the properties of lapply, plus some more.

Tags:

R