๐ŸŽ“ A1Learner
๐Ÿ”
0 of 27 lessons completed

R Vectorised Choice

ifelse() makes a choice for each element of a vector. Vectorize() turns a function written for one value into one that works over a vector.

Pick a label for each score

The test compares each score with 5. ifelse picks high where the test is TRUE and low where it is FALSE.

scores <- c(3, 8, 5, 9)
print(ifelse(scores > 5, "high", "low"))

Pick numbers and words

The first call picks numbers and the second picks words. ifelse keeps the type of the two picked values.

print(ifelse(c(4, 9, 6, 12) >= 6, 1, 0))
marks <- c(45, 80, 62, 91)
print(ifelse(marks >= 50, "pass", "fail"))

A function for one value

size_label uses a plain if to pick one branch. Each call takes a single number and gives back a single label.

size_label <- function(x) {
  if (x >= 10) {
    return("big")
  }
  return("small")
}
print(size_label(12))
print(size_label(4))

Vectorize the function

Vectorize wraps size_label and the new function takes a whole vector. Each element gets its own label in one call.

size_label <- function(x) {
  if (x >= 10) {
    return("big")
  }
  return("small")
}
vsize <- Vectorize(size_label)
print(vsize(c(3, 12, 7, 20)))

Vectorize over two vectors

bigger_label compares one pair of values. The wrapped form pairs the two vectors up and labels each pair.

bigger_label <- function(a, b) {
  if (a >= b) {
    return("first")
  }
  return("second")
}
vbigger <- Vectorize(bigger_label)
print(vbigger(c(5, 2, 9), c(3, 4, 9)))

Example

scores <- c(42, 78, 55, 90)
print(ifelse(scores >= 60, "pass", "fail"))
band <- function(x) {
  if (x >= 60) {
    return("high")
  }
  return("low")
}
vband <- Vectorize(band)
print(vband(scores))

Key points

  • ifelse() takes a test, a value for TRUE and a value for FALSE.
  • The test is a comparison that gives one TRUE or FALSE for each element.
  • The result holds one picked value for each element, in the same order.
  • A function with a plain if inside picks one branch for one value.
  • Vectorize() wraps that function and applies it to each element in turn.
  • The wrapped function can take two vectors and pair their elements up.

In this example, ifelse labels the scores pass or fail in one call. The Vectorize form of band then labels the same scores high or low, with the plain if inside band doing the picking for each element.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does Vectorize() return?