Description Usage Arguments Details Value Warning References See Also Examples
Binary operator to simplify null expressions
1 | x %??% y
|
x |
A value that is possible |
y |
A value that is not |
The objective of the null coalescing operator is to simplify the expression:
if(is.null(x)){ y else { x }}
so that it is readable inline.
Returns the value of the left hand side (LHS) if it is not null, else
returns the value of the right hand side (RHS) that may be NULL
.
Due to the way objects are created within R, the NULL
value
is not able to be stored within atomic vectors
.
However, the NULL
value can be stored within a list
.
This operator will not be triggered if NULL
is within
a list! That is, the RHS side will be returned.
https://en.wikipedia.org/wiki/Null_coalescing_operator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | # Null value
x = NULL
# Before
y = if(is.null(x)){ "Unset" } else { x }
# After
y = x %??% "Unset"
# Concrete examples without variables
# Returns 3 as the LHS is _not_ NULL
3 %??% 4
# Returns 1 as the LHS is _not_ NULL
1 %??% NULL
# Returns 2 as the LHS is NULL
NULL %??% 2
# Coalesce operator
NULL %??% NULL %??% 5
# Coalesce operator
NULL %??% 7 %??% 8
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.