null_coalesce: Null Coalescing Operator

Description Usage Arguments Details Value Warning References See Also Examples

Description

Binary operator to simplify null expressions

Usage

1
x %??% y

Arguments

x

A value that is possible NULL

y

A value that is not NULL

Details

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.

Value

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.

Warning

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.

References

https://en.wikipedia.org/wiki/Null_coalescing_operator

See Also

is.null, NULL

Examples

 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

coatless/rops documentation built on May 13, 2019, 8:47 p.m.