typestar

Conditionals in R

Branching, and its vectorized alternative.

grade <- function(score) {
  if (score >= 90) {
    "A"
  } else if (score >= 80) {
    "B"
  } else {
    "F"
  }
}

marks <- sapply(c(95, 85, 40), grade)
vectorized <- ifelse(c(95, 85, 40) >= 80, "pass", "fail")

How it works

  1. An if/else if chain returns the matching branch.
  2. sapply applies the function across a vector.
  3. ifelse is the vectorized form, testing every element.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
193
Tokens
70
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 49 seconds.

Type this snippet

Step 1 of 5 in Flow & functions, step 5 of 20 in Language basics.

← Previous Next →

Conditionals in other languages