warning, stop

Use these functions to return a warning or error from another function. The warning function will output a message after a function finishes, while the stop function both stops the execution of the function and outputs an error message.
warning(char)
  • char – A character string that is output to the user.
stop(char)
  • char – A character string that is output to the user.

Example. Below is a toy example showing the use of the warning and stop functions. This example is a modified version of the myFactorial function in the Recall post. An error is output if the argument n is less than zero. If the argument is positive but not equal to an integer, then the calculation is accomplished using the factorial function; a warning is output to make clear that the value wasn’t computed using anything but a default function in R. Finally, if the value is a positive integer, then we use the Recall function to recursively call myFactorial (until n=0) and compute the factorial of n.
> myFactorial <- function(n){
+   if(n < 0){
+     stop('The argument "n" must be positive')
+   } else if(n != round(n)){
+     warning('The "factorial" function was used')
+     return(factorial(n))
+   } else if(n > 0){
+     return(n*Recall(n-1))
+   } else {
+     return(1)
+   }
+ }
> 
> myFactorial(4)
[1] 24
> myFactorial(3.5)
[1] 11.63173
Warning message:
In myFactorial(3.5) : The "factorial" function was used
> myFactorial(-1)
Error in myFactorial(-1) : The argument "n" must be positive
Tip. One rule in online web development is to never trust user input (the usual quote is all user input is evil). While there aren’t security issues in R that warrant as strong of a concern, it is still important that user input is checked if for no other reason than to provide thoughtful feedback when something is wrong.

Leave a Reply