You may want to put some error handling in your functions.
S-PLUS has a few functions which do this: stop
and warning
. The function stop
will return an
error and terminate the function, while warning
will return an error message but continue executing the function.
The following standard deviation function works the same as
before but returns an error if its argument is not a vector
(the exclamation point before is.vector
means ``negation'',
so the error message appears ``if x is not a vector'').
> stdev <- function(x) + { + # stdev with error handling + if(!is.vector(x)) + stop("The argument to stdev must be a vector") + else sqrt(var(x)) + }As an example, consider the vector
z
which was used to
test the standard deviation function before, and z
after it is converted to a matrix.
> stdev(z) [1] 1.395708 > z <- as.matrix(z) > stdev(z) Error in stdev(z): The argument to stdev must be a vector DumpedS-PLUS returns the error message verbatim (so when you write error messages, make sure that they are informative).