The Wayback Machine - https://web.archive.org/web/20250114033703/https://www.geeksforgeeks.org/switch-case-in-r/
Open In App

Switch case in R

Last Updated : 21 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Switch case

statements are a substitute for long if statements that compare a variable to several integral values. Switch case in R is a multiway branch statement. It allows a variable to be tested for equality against a list of values. Switch statement follows the approach of mapping and searching over a list of values. If there is more than one match for a specific value, then the switch statement will return the first match found of the value matched with the expression.

Syntax:

switch(expression, case1, case2, case3....)

Here, the expression is matched with the list of values and the corresponding value is returned.

Important Points about Switch Case Statements:

  • An expression type with character string always matched to the listed cases.
  • An expression which is not a character string then this exp is coerced to integer.
  • For multiple matches, the first match element will be used.
  • No default argument case is available there in R switch case.
  • An unnamed case can be used, if there is no matched case.

Flowchart:

Example 1:

Python3 1==
# Following is a simple R program  
# to demonstrate syntax of switch.
val <- switch(
   4,
   "Geeks1",
   "Geeks2",
   "Geeks3",
   "Geeks4",
   "Geeks5",
   "Geeks6"
)
print(val)

Output:

[1] "Geeks4"

Example 2:

Python3 1==
# Following is val1 simple R program  
# to demonstrate syntax of switch.

# Mathematical calculation

val1 = 6  
val2 = 7
val3 = "s"  
result = switch(  
    val3,  
    "a"= cat("Addition =", val1 + val2),  
    "d"= cat("Subtraction =", val1 - val2),  
    "r"= cat("Division = ", val1 / val2),  
    "s"= cat("Multiplication =", val1 * val2),
    "m"= cat("Modulus =", val1 %% val2),
    "p"= cat("Power =", val1 ^ val2)
)  
  
print(result)  

Output:

multiplication = 42NULL

Enhance your coding skills with DSA Python, a comprehensive course focused on Data Structures and Algorithms using Python. Over 90 days, you'll explore essential algorithms, learn how to solve complex problems, and sharpen your Python programming skills. This course is perfect for anyone looking to level up their coding abilities and get ready for top tech interviews.
Join the Three 90 Challenge and commit to completing 90% of the course in 90 days to earn a 90% refund. It’s the perfect way to stay focused, track your progress, and reap the rewards of your hard work. Take the challenge and become a DSA expert in Python today


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg