Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 4 / 68

Branching (the if statement)

This lesson covers how to write an if statement in R, with the aim of being able to branch on a condition.

if / else if / else branches on a condition. It helps to picture it as translating an everyday judgement — "if it is raining, take an umbrella" — into a program.

The sample code uses if / else if / else to print one of three messages depending on score. Comparisons use >, <, == and so on, and stacking else if branches expresses three or more cases naturally.

A common early stumble is passing a vector of length two or more as the condition. An ordinary if statement expects a single value (a scalar); to apply a condition across a whole vector you need the separate ifelse() function.

In professional work, branching on a condition comes up constantly even in data analysis code.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)