return() # Terminate a function call and return a value.
stop() # Terminate a function call and print an error message.
warning() # Print a warning message (without terminating the
# function call).
Terminating a function with returns, errors, and warnings
The following functions are useful for terminating a function call or just printing a warning message:
Terminating a Function Call Using if()
and return()
One way to terminate a function call is with return()
which, when encountered, immediately terminates the call and returns a value. For example:
<- function(x) {
mySign if(x < 0) return("Negative")
if(x > 0) return("Positive")
return("Zero")
}
Passing mySign()
the value x = 13
produces the following:
mySign(x = 13)
[1] "Positive"
(Note that the last line, return("Zero")
, was never encountered during the call to my.sign()
.)
Terminating a Function Call and Printing an Error Message Using if()
and stop()
Another way to terminate a function call is with stop()
, which then prints an error message without returning a value. Here’s an example:
<- function(x, y) {
myRatio if(y == 0) stop("Cannot divide by 0")
return(x/y)
}
An attempt to pass the value 0
for y
now results in the following:
myRatio(x = 3, y = 0)
Error in myRatio(x = 3, y = 0): Cannot divide by 0
(Note that the last line, return(x/y)
, was never encountered during the call to myRatio()
)
Printing a Warning Message Using if()
and warning()
warning()
just prints a warning message to the screen without terminating the function call. Here’s an example:
<- function(x, y) {
myRatio if(y == 0) warning("Attempt made to divide by 0")
return(x/y)
}
Now when we pass the value 0
for y
the function call isn’t terminated (the special value Inf
is returned), but we get the warning message:
myRatio(x = 3, y = 0)
Warning in myRatio(x = 3, y = 0): Attempt made to divide by 0
[1] Inf
By adding error messages and warnings to you functions it is easier for you and others using your scripts to figure out what went wrong if your script doesn’t return the anticipated answer.