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

The switch() function

This lesson covers branching on several conditions with R's switch(), with the aim of organising conditions more readably than an if statement can.

switch() reads better than a stack of if / else if when you want to branch on a single value. What is distinctive in R is that switch is provided as a function.

The sample code selects a message for each string with switch(day, mon = "Monday", tue = "Tuesday", wed = "Wednesday", "Another day"). The final unnamed value is the default when nothing matches.

A common early stumble is how to write that default. There is no default keyword as in other languages — the last value written without a name is treated as the default.

In professional work, switch() is used wherever you branch across a fixed set of options, such as days of the week or status codes.

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