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

Applying a condition across a vector with ifelse()

This lesson covers applying a condition across a vector with R's ifelse(), with the aim of understanding vectorised branching.

ifelse(condition, value_if_true, value_if_false) is the R-idiomatic function that applies a branch to every element of a vector at once. Where an ordinary if statement expects a scalar, ifelse() handles the whole vector.

The sample code judges every element of the ages vector in one line with ifelse(ages >= 20, "Adult", "Minor"), producing the result vector messages. No for loop is required — concise and very R-like.

A common early stumble is the difference from an ordinary if statement. An ordinary if cannot be used across a whole vector, so applying a condition to several values at once always calls for ifelse().

In professional work, ifelse() comes up constantly in data analysis, for instance when applying a condition to a whole column of a data frame.

๐Ÿ“– 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)