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

R If Else

An if statement runs a block of code only when its test is TRUE. An else block runs when the test is FALSE.

Run code when true

The age value passes the test inside the brackets. The block runs and shows adult.

age <- 20
if (age >= 18) {
  print("adult")
}

Choose with else

The score fails the pass test. The else block runs and shows retry.

score <- 45
if (score >= 50) {
  print("pass")
} else {
  print("retry")
}

Add another test

The first test fails for a temperature of 15. The else if test passes and shows mild.

temp <- 15
if (temp < 10) {
  print("cold")
} else if (temp < 20) {
  print("mild")
} else {
  print("warm")
}

A common error

The test uses a single equals sign. The program shows an error instead of running.

score <- 80
if (score = 80) {
  print("pass")
}

Example

mark <- 72
if (mark >= 90) {
  print("top")
} else if (mark >= 60) {
  print("good")
} else {
  print("keep going")
}

Key points

  • The test sits inside round brackets after if.
  • Curly braces hold the block that runs.
  • An else if part adds one more test in the middle.
  • A final else part catches every case left over.
  • The test must give a single TRUE or FALSE value.
  • The symbol == tests a value inside the test.

In this example, the first test fails for a mark of 72. The else if test passes, so the block prints good.

Note

The symbol = assigns a value, and R does not accept it inside an if test.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

Which symbol tests equality inside an if test?