fixNull: Replace a null value

View source: R/missingValues.R

fixNullR Documentation

Replace a null value

Description

Returns the value x, unless x is NULL, in which case it returns either val or, if val is NULL (the default), it returns the result of calling the function func. Additional ... parameters will be passed to func if called. If both a replacement value and function are specified, the replacement value is returned but the function is still called for its side effects. Its return value will be ignored. This can be used e.g. with a "warning" or a logging function to report when a replacement occurs. Leaving both val and func at their default NULL values means this function will have no net effect, i.e. it will replace NULL with NULL. Note, due to R's argument parsing, if you want to call func and pass it unnamed parameters via ..., val= NULL must be set.

Usage

fixNull(x, val = NULL, func = NULL, ...)

Arguments

x

Check this to see if this is NULL.

val

Return this value if x is NULL. Default is NULL.

func

Called to generate and return a replacement value, unless val is set, in which case that is returned; any value returned by func is ignored. Can be a bare function name, string, or function definition.

...

Additional parameters to pass to func, if any. If any are unnamed, val must be specified or explicitly set NULL. If val is not specified, then due to R's parameter parsing, the first unnamed extra parameter will be used as the value of val instead of being passed to the function. That means it will also be returned as the NULL replacement value. This "parameter swallowing" is a potential issues with all functions using "..." with parameters that have default values. Handling of this may change in future implementations.

Value

x, or if that is NULL then val, or if that is NULL the result of calling func with any parameters ..., or NULL if both val and func are NULL. If both val and func are set, val will be returned, but func will still be called for any potential side effects.

Examples

fixNull( 42, -1 )
#> 42

fixNull( NULL, -1 )
#> -1

fixNull( NULL )
#> NULL

## Not run: 
# Return `val`, calling function only for side effect.
# Val is specified, so no issue with unnamed parameters
fixNull( NULL, 42, func="warning", "Was NULL" )
#> 42
#> Warning message:
#> In fixNull( NULL, func="warning", "Failed!" ) : Was NULL

## End(Not run)

# Calling function (with extra parameter) to generate replacement value.
# Extra parameter is named, so no issue with unspecified `val`.
fixNull( NULL, func= function( num ) { num * log(num) }, num= 42 )
#> [1] 156.9821

# Calling function (with extra parameters) to generate replacement value.
# Some extra  parameters are unnamed, so must specify `val= NULL`.
fixNull( NULL, val=NULL, func= paste, "this", "that", sep= "-" )
#> [1] "this-that"

jefferys/JefferysRUtils documentation built on Jan. 12, 2024, 9:18 p.m.