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:

Original function:

iq_classification <- function(score){
  if(score >= 130){
      "Very superior"
  } else {
      "Not very superior"
  }
}

Vectorized function with for-loop:

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.

Exercise