In a previous exercise 3.3.2 you wrote the iq_classification(score)
function in a way it can handle score vectors with lengths greater than 1 using the ifelse
function. This ifelse
is perfect for vectorizing a very specific subset of functions (if-statements), a more uniform way could be using a for-loop:
iq_classification <- function(score){
if(score >= 130){
"Very superior"
} else {
"Not very superior"
}
}
iq_classification_for <- function(scores){
results <- c()
for(score in scores){
if(score >= 130){
results <- append(results, "Very superior")
} else {
results <- append(results, "Not very superior")
}
}
results
}
For loops are very usefull and sometimes inevitable but for most cases R has provided functions to avoid for-loops. These functions tend to be faster and shorter to write. The apply family is a widely used set of functions that can be used to replace for loops.
Apply family functions |
---|
apply() |
lapply() |
sapply() |
vapply() |
mapply() |
rapply() |
tapply() |
All these functions are meant to vectorize functions that normally can’t handle vectors with a length greater than 1. Most of these fall out of scope for this basic introduction but there is one in particular that will be very handy, the sapply()
function.
Write a wrapper function iq_classification_wrapper
that vectorizes the original iq_classification
function using the sapply
function (This wrapper function should accept vectors with lengts greater than 1).
Wrapper functions
A wrapper function is a function whose main purpose is to call a second function with little or no additional computation.
Avoid duplication of effort
We have written the original
iq_classification(score)
function for you. This function returns the corresponding IQ category for a givenscore
.