Learn R Programming

MazamaCoreUtils (version 0.6.2)

stopIfNull: Stop if an object is NULL

Description

Convenience function for validating that an object is not NULL.

Usage

stopIfNull(target, msg = NULL)

Value

Invisibly returns target when it is not NULL.

Arguments

target

Object to test.

msg

Optional error message to display if target is NULL. Must be a character string of length one.

Details

If target is not NULL, it is returned invisibly. If target is NULL, the function stops with either a default or user-supplied error message.

This function is especially useful for validating required function arguments or for guarding intermediate results in pipelines.

Examples

Run this code
# Return input invisibly if not NULL
x <- stopIfNull(5)
print(x)

# Useful in pipelines
y <- 1:10
y_mean <-
  y %>%
  stopIfNull() %>%
  mean()

if (FALSE) {
# Trigger the default error message
testVar <- NULL
stopIfNull(testVar)

# Trigger a custom error message
stopIfNull(testVar, msg = "This is NULL")

# Make a failing pipeline
z <- NULL
z_mean <-
  z %>%
  stopIfNull("This has failed.") %>%
  mean()
}

Run the code above in your browser using DataLab