0
0
R Programmingprogramming~5 mins

Switch statement in R Programming

Choose your learning style9 modes available
Introduction

A switch statement helps you choose one action from many options based on a value. It makes your code cleaner and easier to read than many if-else checks.

You want to run different code depending on a variable's value.
You have many possible cases to check and want to avoid long if-else chains.
You want to make your code easier to understand by grouping choices clearly.
You want to return different results based on user input or function arguments.
Syntax
R Programming
switch(expression, case1 = value1, case2 = value2, ..., default)

The expression is what you check against the cases.

If the expression matches a case name, the corresponding value is returned.

Examples
This checks the number 2 and returns the second value, which is "two".
R Programming
result <- switch(2, "one", "two", "three")
print(result)
This checks the string "b" and returns "banana" because it matches case b.
R Programming
result <- switch("b", a = "apple", b = "banana", c = "cherry")
print(result)
Since "x" does not match any case, it returns the default value "default fruit".
R Programming
result <- switch("x", a = "apple", b = "banana", c = "cherry", "default fruit")
print(result)
Sample Program

This program uses a switch statement to find the meaning of a color. It prints "go" because the choice is "green".

R Programming
choice <- "green"
color_meaning <- switch(choice,
                       red = "stop",
                       yellow = "caution",
                       green = "go",
                       "unknown color")
print(color_meaning)
OutputSuccess
Important Notes

If no case matches and no default is given, switch() returns NULL.

Case names can be numbers or strings, but they must match the expression type.

Switch is useful for simple choices but not for complex conditions.

Summary

Switch lets you pick one result from many options based on a value.

It makes code cleaner than many if-else statements.

Always include a default case to handle unexpected values.