<- calculate_mean(c("cat", "dog", "horse")) result
Error in total + value: non-numeric argument to binary operator
Your function works well, but what would happen if the wrong arguments were passed? Let’s check what happens with our function calculate_mean
.
<- calculate_mean(c("cat", "dog", "horse")) result
Error in total + value: non-numeric argument to binary operator
This isn’t very descriptive or helpful. Fortunately, you can control how R will behave in an error condition by using stop
or warning
.
You use stop
if you want to stop the function from continuing, and to print an error message for the user. For example, we could use is.numeric
function to check if all of the values are numeric. If not, then we could call stop
.
<- function(values){
calculate_mean <- 0.0
total <- 0
count for (value in values){
if (!is.numeric(value)){
stop("Cannot calculate average of non-numeric values")
}<- total + value
total <- count + 1
count
}return(total / count)
}
<- calculate_mean(c("cat", "dog", "horse")) result
Error in calculate_mean(c("cat", "dog", "horse")): Cannot calculate average of non-numeric values
This is a much more useful error message! However, what if instead of stopping, we want to calculate the average of any numeric values, and just warn the user if non-numeric values are passed? We can do this using the warning
function:
<- function(values){
calculate_mean <- 0.0
total <- 0
count for (value in values){
<- as.numeric(value)
number
if (!is.na(number)){
<- total + number
total <- count + 1
count else {
} warning("Skipping '", value,
"' as it is not numeric")
}
}return(total / count)
}
<- calculate_mean(c("cat", "dog", "horse")) result
Warning in calculate_mean(c("cat", "dog", "horse")): NAs introduced by coercion
Warning in calculate_mean(c("cat", "dog", "horse")): Skipping 'cat' as it is
not numeric
Warning in calculate_mean(c("cat", "dog", "horse")): NAs introduced by coercion
Warning in calculate_mean(c("cat", "dog", "horse")): Skipping 'dog' as it is
not numeric
Warning in calculate_mean(c("cat", "dog", "horse")): NAs introduced by coercion
Warning in calculate_mean(c("cat", "dog", "horse")): Skipping 'horse' as it is
not numeric
In this case, we try to convert the value into a number using the as.numeric
function. If this fails, it will return NA
. We then test for NA
using the is.na
function, printing a warning that we are skipping this value if it isn’t a number.