EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Data Science Data Science Tutorials R Programming Tutorial Switch Statement in R
 

Switch Statement in R

Priya Pedamkar
Article byPriya Pedamkar

Updated March 22, 2023

Switch Statement in R

 

 

Introduction to Switch Statement in R

Switch Statement in R language is a control statement that is used to move the program control to one code line or module to another which is based upon the condition specified in the program. The switch statement is mostly used in the case of multiple condition check with a list of values scenarios in the R language. The list of values associated with switch statements is known as cases. R language supports a built-in function called switch() which is used to apply the switch case logic in the R program. The switch statement in R accepts the expression and the cases as function parameters for the evaluation of the cases for developing the program logic.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

So here we can use Switch statements in r which have multiple advantages, like

  • A switch statement can tests expressions based on a String object, List value, or single integer, basically, in simpler terms, we can say that the switch statements are best for fixed data values.
  • Switch Statements are better for multi-way branching.
  • Speed of processing of code is fast when we use switch statements (this is visible when there are a significant number of cases); generally, if-else statements took time when there is a large number of cases.
  • Switch statements are less vulnerable to error as they are much cleaner when we have to combine cases.

Definition

A switch statement will compare the expression value and the values present in the list and provide us the best output which meets all the requirements. Now we will see some illustration where we can use the switch statement.

Syntax:

The basic syntax in R for switch Statements looks like:

switch(expression, Value 1, Value 2, Value 3.... Value n)

Here, the code will compare expression value with the values in the list and the best match will return as an output that fulfills every condition of the problem statement.

Rules of Switch Statement

The rules which are applicable in Switch Statement are:

1. There is no limit for case statements within a switch like you can form n numbers of case statements, the only limitation is each case is followed by the value to be compared to or a colon wherever the character string is.

2. If there is more than one match within a switch statement, the first matching case statement is returned as an output.

Example #1

Code:

x <- switch("color","color" = "red", "shape" = "square","color" = "blue")
x

Output:

Switch Statement in R 1-1

Code:

x <- switch("color","color" = "blue", "shape" = "square","color" = "red")
x

Output:

Switch Statement in R 1-2

3. If the value we have to evaluate in our code is a number and numeric value is out of range (Values are greater than the number of items in the list or smaller than 1). Then the outcome returned to us is “NULL”.

Example #2

Code:

x <- switch(4,"Ball","Bat","Wickets")
x

Output:

Switch Statement in R 1-3

Code:

x <- switch(0, "Ball","Bat","Wickets")
x

Output:

Switch Statement in R 1-4

4. If we have to evaluate a character string than character strings should be matched exactly to the names of the elements.

Example #3

Code:

x <- switch("color","color" = "red", "shape" = "square")
x

Output:

Switch Statement in R 1-5

Code:

x <- switch("coler", "color" = "red", "shape" = "square")
x

Output:

Switch Statement in R 1-6

5. We will get an error as a result only when there is more than one case statement with wrong spelling or that expression is not in the list or the corresponding value of the case statement is missing.

Flow Diagram of Switch Statement in R

Flow Diagram

  • If Expression = Case 1, STATEMENT 1 is executed.
  • If Expression = Case 2, STATEMENT 2 is executed.
  • If Expression = Case 3, STATEMENT 3 is executed.
  • If Case 1, Case 2, and Case 3 fail then the Default Statement is executed.

Use Cases of Switch Statement

Some Cases where we can use switch statements.

Type 1: If The Expression Is Number

Code:

switch(2, "Ball","Bat","Wickets")

Output:

Switch Statement in R 1-7

Code:

switch(3, "Ball","Bat","Wickets")

Output:

Switch Statement in R 1-8

In the above example, we have a list which consists of three elements (Ball, Bat, and Wickets), the switch statement function will return the corresponding item to the numeric value which we entered as an expression.

Here we have to closely follow the rules while using a Switch statement, like the very basic and common error is:

“If the value evaluated is a number and numeric value is out of range (Values are greater than the number of items in the list or smaller than 1). The outcome returned to us is “NULL ”.

Code:

x <- switch(4,"Ball","Bat","Wickets")
x

Output:

Switch Statement in R 1-9

Type 2: If The Expression Is String

Code:

switch("Wickets", "Ball" = "Red", "Bat" = "Rectangle", "Wickets" = "Out")

Output:

Expression Is String 1-10

Flow Diagram for the Example looks like:

Flow Diagram Expression Is String-1.2

Type 3: Mix n Match

Example #1:

x= 1
y = 2
z = switch(x+y,  "Hello Abhinav", "Hello Mayank", "Hello Naman", "Hello Hardik")

Here we assigned some values to x and y then we add expression in the switch statement as an equation.

So x+y = 1+2 = 3.

Which means 3rd value in the list will come as an output. In our example, the 3 value is “Hello Naman”.

Code:

And the code for the above example looks like this:

x= 1
y = 2
z = switch(x+y,  "Hello Abhinav", "Hello Mayank", "Hello Naman", "Hello Hardik")
z

Output:

Switch Statement in R 1-11

Example #2:

Where x= 1 and y= 7
a = switch(paste(x,y,sep=""),  "7"="Hello Abhinav", "12"="Hello Mayank", "17"="Hello Naman", "21"="Hello Hardik")

When we run this in R we will get.

Code:

x= 1
y= 7
a = switch(paste(x,y,sep=""),  "7"="Hello Abhinav", "12"="Hello Mayank", "17"="Hello Naman", "21"="Hello Hardik")
a

Output:

Example 1-12

Conclusion

  • Switch statements are easier to read.
  • Switch statements are more efficient if we compare it with the If-Else statement.
  • Switch Statements are easy to maintain and write.
  • With the help of the Switch Statement, we can make a jump table.
  • Switch statements help us to make large code very handy, it is very easy to trace an error in the code if any.

Though there are some limitations also like Switch statements doesn’t work with floats and also it doesn’t work with ranges (unless explicitly mentioned).

Recommended Articles

This is a guide to Switch Statement in R. Here we discuss the Rules, flow diagram and different uses cases of switch Statements in R with examples. You may also look at the following articles to learn more –

  1. Switch Statement in C
  2. Switch Statement in C++
  3. Switch Statement in JavaScript
  4. Switch Statement in Matlab
  5. Switch Statement in C#
  6. PowerShell Switch Statement

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW