-
Notifications
You must be signed in to change notification settings - Fork 1k
Closed
Labels
Description
Consider trying to extract an element of a list that might not exist:
sapply(l, function(x) x$a)
if a
is missing from any element of l
, the output will be a list
, otherwise it'll be a vector.
There are a few clumsy workarounds e.g.
sapply(l, function(x) if ('a' %chin% names(x)) x$a else 1)
sapply(l, function(x) { y <- x$a; if (is.null(y)) 1 else y})
All are harder to read* than
sapply(l, function(x) fcoalesce(x$a, 1))
The idea would be to essentially treat NULL
as NA
within fcoalesce
. The overhead should be low since we can do this up front. Currently not so:
fcoalesce(NULL, 1)
# NULL
fcoalesce(NA, NULL, 1)
# Error: Item 2 is type NULL but the first item is type logical. Please coerce before coalescing.
*(this is always subjective but I particularly have in mind users who are comfortable with SQL)