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

R Switch

A switch statement picks one value from a list of choices. The choice is picked by name or by position.

Pick by name

The value Tue matches one named choice. The print shows the text stored with that name.

day <- "Tue"
print(switch(day, Mon = "gym", Tue = "swim", Wed = "run"))

Pick by position

The number 2 picks the second choice in the list. The print shows that choice.

print(switch(2, "a", "b", "c"))

No matching name

The value Fri matches no named choice here. The print shows NULL.

print(switch("Fri", Mon = "gym", Tue = "swim"))

Example

size <- "M"
print(switch(size, S = "small cup", M = "medium cup", L = "large cup"))

Key points

  • The first value inside switch says what to match.
  • A named choice matches when its name equals the value.
  • An unnamed choice is picked by its position number.
  • A match gives back the value stored with that choice.

In this example, the value M matches the second named choice. The switch gives back the text stored with that name.

Note

A name with no matching choice gives NULL.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does print(switch(3, "a", "b", "c")) show?