EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

Switch Statement in R

By Priya PedamkarPriya Pedamkar

Home » Data Science » Data Science Tutorials » R Programming Tutorial » Switch Statement in R

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.

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

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

  • 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.

Popular Course in this category
R Programming Training (12 Courses, 20+ Projects)12 Online Courses | 20 Hands-on Projects | 116+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,998 ratings)
Course Price

View Course

Related Courses
Statistical Analysis Training (10 Courses, 5+ Projects)All in One Data Science Bundle (360+ Courses, 50+ projects)

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

R Programming Training (12 Courses, 20+ Projects)

12 Online Courses

20 Hands-on Projects

116+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
R programming Tutorial
  • Control statement
    • If Statement in R
    • If Else Statement in R
    • Else if in R
    • Switch Statement in R
  • Basic
    • What is R Programming Language
    • Careers in R Programming
    • Install R
    • List of R Packages
    • Introduction of R Tools Technology
    • R Programming Language
    • What is RStudio?
    • R-studio-Functions
    • R Packages
    • R Data Types
    • R Operators
    • Vectors in R
  • Loops
    • Loops in R
    • For Loop in R
    • Nested For Loop in R
    • While Loop in R
    • Next in R
  • Chart/graphs
    • Graphs in R
    • Bar Charts in R
    • Pie Chart in R
    • Histogram in R
    • Line Graph in R
    • Plot Function in R
    • Scatterplot in R
    • R Boxplot labels
  • Regression in R
    • Simple Linear Regression in R
    • Linear Regression in R
    • Multiple Linear Regression in R
    • Logistic Regression in R
    • Poisson Regression in R
    • OLS Regression in R
    • P-Value in Regression
  • Anova in R
    • ANOVA in R
    • One Way ANOVA in R
    • Two Way ANOVA in R
  • Data Structure
    • R list
    • Arrays in R
    • Data Frames in R
    • Factors in R
  • Advanced
    • Statistical Analysis with R
    • R String Functions
    • Data Exploration in R
    • R CSV Files
    • KNN Algorithm in R
    • Sorting in R
    • lm Function in R
    • Hierarchical Clustering in R
    • R Normal Distribution
    • Binomial Distribution in R
    • Decision Tree in R
    • GLM in R
    • Linear Model in R
    • Predict Function in R
    • Survival Analysis in R
    • Standard Deviation in R
    • Statistical Analysis in R
    • T-test in R
    • Database in R
  • Programs
    • R Program Functions
    • Factorial in R
    • Random Number Generator in R
  • Interview question
    • R Interview Questions

Related Courses

R Programming Certification Course

Statistical Analysis Course Training

All in One Data Science Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

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

EDUCBA Login

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

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

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

Special Offer - R Programming Training (12 Courses, 20+ Projects) Learn More