Returns default when target is NULL; otherwise returns target
unchanged.
setIfNull(target, default, enforcedType = NULL)Object to test for NULL.
Object to return when target is NULL.
Optional character string specifying the suffix of an
as.*() coercion function to apply to the returned value. For example,
"double" uses as.double(), "character" uses as.character(),
and "Date" uses as.Date().
If NULL (the default), no coercion is performed.
The value of target if it is not NULL; otherwise default.
If enforcedType is specified, the returned value is coerced using the
corresponding as.*() function.
This is useful for assigning default values to optional arguments while preserving any user-supplied value exactly as provided.
Optionally, enforcedType may be used to coerce the returned value to a
specific type. This coercion is applied after the NULL check and affects
both target and default.
setIfNull(NULL, "foo")
#> [1] "foo"
setIfNull(10, 0)
#> [1] 10
setIfNull("15", 0)
#> [1] "15"
# User-supplied values are returned unchanged
setIfNull("15", 0)
#> [1] "15"
setIfNull("mean", 0)
#> [1] "mean"
setIfNull(mean, 0)
#> function (x, ...)
#> UseMethod("mean")
#> <bytecode: 0x113d3a5f0>
#> <environment: namespace:base>
# Optional type enforcement
setIfNull("15", 0, enforcedType = "double")
#> [1] 15
setIfNull(NULL, "15", enforcedType = "integer")
#> [1] 15