13.2 Checking values
By default, once a function is called, all code inside the function will be executed. However, there may be cases where there’s no point in evaluating parts of the code and it’s best to stop everything and leave the function altogether. This might not seem so important at the moment as we’ve only dealt with a small number of neat little functions. But imagine you’re writing complex code, maybe an entire R package, that will be used by people that don’t know logic. How will you make sure that these users call every function the way you want it to be called?
As an example, let’s create a new function calculateWeightedMean() that calculates the mean of vector x using vector weights as weights:
What happens if x and weights are not the same length?
Although the functions runs and produces a result (as R recycles the shorter vector weights), this might not be what you want. Instead, you would like to tell the user he’s doing something wrong, and then stop the execution of the code, instead of wasting time for a useless result. We can achieve this with the function stop(). If R ever executes a stop() function, it will directly quit the function it’s currently evaluating, and print an error message. You can define the exact error message as an argument for stop():
> calculateWeightedMean <- function(x, weights) {
+ if (length(x) != length(weights)) {
+ stop("Wow, stop!! Arguments 'x' and 'weights' must have the same length!")
+ }
+ return(sum(x * weights) / sum(weights))
+ }Let’s call the function with an invalid argument: two vectors of different length:
> calculateWeightedMean(1:5, 100:10000)
Error in calculateWeightedMean(1:5, 100:10000): Wow, stop!! Arguments 'x' and 'weights' must have the same length!With valid arguments, the function will run as before:
13.2.1 Exercises: Checking values
See Section 18.0.34 for solutions.
- Write a function that converts Kelvin to Fahrenheit. Consider that the absolute zero temperature is 0 Kelvin, hence negative values are invalid. Throw an error if a user enters invalid values!