An if statement chooses which block runs. The condition is a logical value computed from current data.

Program

Play the script to watch a score choose the passing branch.

score
branches.R
Replay: real traced execution (multi-file project)
score <- 82
if (score >= 80) {
  grade <- "pass"
} else {
  grade <- "retry"
}
cat(grade, "\n", sep = "")
score <- 60
if (score >= 80) {
  grade <- "pass"
} else {
  grade <- "retry"
}
cat(grade, "\n", sep = "")
score <- 95
if (score >= 80) {
  grade <- "pass"
} else {
  grade <- "retry"
}
cat(grade, "\n", sep = "")
  1. score ← 82

    1score <- 822if (score >= 80) {
    values this step82score
  2. score >= 80 ← TRUE

    1score <- 822if (score >= 80) {3  grade <- "pass"
    values this stepTRUEscore >= 8082score
  3. grade ← pass

    2if (score >= 80) {3  grade <- "pass"4} else {
    values this steppassgrade
  4. cat(grade, " ", sep = "")

    6}7cat(grade, "\n", sep = "")
    outputpass
    values this steppassgrade
  1. score ← 60

    1score <- 602if (score >= 80) {
    values this step60score
  2. score >= 80 ← FALSE

    1score <- 602if (score >= 80) {3  grade <- "pass"
    values this stepFALSEscore >= 8060score
  3. grade ← retry

    4} else {5  grade <- "retry"6}
    values this stepretrygrade
  4. cat(grade, " ", sep = "")

    6}7cat(grade, "\n", sep = "")
    outputretry
    values this stepretrygrade
  1. score ← 95

    1score <- 952if (score >= 80) {
    values this step95score
  2. score >= 80 ← TRUE

    1score <- 952if (score >= 80) {3  grade <- "pass"
    values this stepTRUEscore >= 8095score
  3. grade ← pass

    2if (score >= 80) {3  grade <- "pass"4} else {
    values this steppassgrade
  4. cat(grade, " ", sep = "")

    6}7cat(grade, "\n", sep = "")
    outputpass
    values this steppassgrade

Choose the Grade

  1. score starts at 82.
  2. score >= 80 evaluates to TRUE.
  3. The if branch sets grade to pass.
  4. Lower scores would use the else branch and become retry. | Score | Condition | Grade | | --- | --- | --- | | 82 | TRUE | pass | | 60 | FALSE | retry |
if `if (condition)` runs the following block only when the condition is `TRUE`.
comparison `score >= 80` returns a logical value.
else `else` gives the fallback path when the condition is `FALSE`.

Exercise: branches.R

Use an if/else branch to print pass for scores at least 80 and retry otherwise