Is there a method to stop lapply()
from returning NULL values for each element of the list when a function doesn't have a return()
.
Here's a pretty basic example:
x <- function(x) { return(NULL) } a.list <- list(a=1,b=2,c=3) lapply(a.list, x)
The output is:
$a NULL $b NULL $c NULL
My goal is to not have that output, at all.
Update: my usage case is as follows. I'm using lapply()
to pump out xtable()
text and I'm sink()
'ing it to an Rnw file. So this NULL output is bugging up my automation.
If your function is usually returns something but doesn't for some reason, return null; is the way to go. That's similar to how you do it e.g. in C: If your function doesn't return things, it's void , otherwise it often return either a valid pointer or NULL.
The lapply() function helps us in applying functions on list objects and returns a list object of the same length. The lapply() function in the R Language takes a list, vector, or data frame as input and gives output in the form of a list object.
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.
JavaScript uses the null value to represent the intentional absence of any object value. If you find a variable or a function that returns null , it means that the expected object couldn't be created.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With