0
0
R-programmingHow-ToBeginner · 3 min read

How to Use switch in R: Syntax and Examples

In R, switch() selects a value based on a given expression or string. You provide a test value and a set of options, and switch() returns the matching option or a default if no match is found.
📐

Syntax

The switch() function has two main forms depending on the type of the first argument:

  • Numeric form: switch(EXPR, option1, option2, ...) where EXPR is a number selecting the option by position.
  • Character form: switch(EXPR, name1 = option1, name2 = option2, ...) where EXPR is a string matching one of the names.

If no match is found, switch() returns NULL or the first unnamed option if numeric and out of range.

r
switch(EXPR, ...)

# Numeric example:
switch(2, "apple", "banana", "cherry")  # returns "banana"

# Character example:
switch("b", a = "apple", b = "banana", c = "cherry")  # returns "banana"
💻

Example

This example shows how to use switch() with a character input to select a fruit name and with a numeric input to select a color.

r
fruit <- "b"
result1 <- switch(fruit,
                  a = "apple",
                  b = "banana",
                  c = "cherry",
                  "unknown fruit")

number <- 3
result2 <- switch(number,
                  "red",
                  "green",
                  "blue",
                  "unknown color")

print(result1)
print(result2)
Output
[1] "banana" [1] "blue"
⚠️

Common Pitfalls

Common mistakes include:

  • Using numeric EXPR with named options, which will not work as expected.
  • Not providing a default option, causing switch() to return NULL if no match is found.
  • Confusing numeric and character forms of switch().
r
wrong <- switch(2, a = "apple", b = "banana")  # returns NULL because numeric index ignores names

right <- switch("b", a = "apple", b = "banana")  # returns "banana"
📊

Quick Reference

Tips for using switch() in R:

  • Use numeric EXPR to select by position.
  • Use character EXPR to select by name.
  • Always provide a default option to avoid NULL results.
  • switch() returns the matched option or NULL if no match and no default.

Key Takeaways

Use switch() to select values based on a number or string expression.
Numeric EXPR selects options by position; character EXPR selects by name.
Always include a default option to handle unmatched cases.
Avoid mixing numeric EXPR with named options to prevent unexpected NULL results.