Hello, readers! In this article, we will be focusing on R switch() function in detail. So, let us begin!! 🙂
Usage of the R switch() function
The object-Oriented Programming paradigm is an important aspect of any programming language.
We often come across various selection statements such as if statement, switch statement, etc.
switch() function in R is the same as the switch-case statements that many programming languages offer.
The switch() function enables us to create conditional statements without using multiple “if-else” conditions.
Having said that, if switch() finds more than one matching value, it returns the first match from the range of matched values.
switch(expression, case1, case2, case3....)
expression: The entity to be searched against equality.
Let us now try to implement the concept of switch() case in the below scenarios.
1. The switch() – Simple Implementation
In this example, we have performed a simple implementation of switch() function in R.
rm(list = ls()) res <- switch( 3, "Pune", "Satara", "Mumbai", "Nashik" ) print(res)
Here, we have passed ‘3’ as the expression to be evaluated. In this case, the value at index ‘3’ would be returned.
2. R expression outputs with the switch() function
Apart from testing against equality, we can even evaluate expressions within the switch() function and then check for equality against an expression.
rm(list = ls()) x = 1000 y = 100 res <- switch( 't', 'a'=print(x*y), 't'=print(x/y), 'c'=print(x*x) )
When the system encounters the switch() function, it searches for the matching entity against the expression and then evaluates the expression ahead of it.
3. R switch() function with multiple match cases
Apart from evaluating the arithmetic expressions and testing for equality, we can also test the equality against multiple expressions having same values.
In such scenario, when a switch() function encounters multiple matching cases from the arguments, it selects the first first match encountered and returns the same.
Have a look at the below code!
rm(list = ls()) code = 'y' fruit <- switch(code, "y"="banana", "y"="pineapple", "z"="berries") print(fruit)
Above, the switch() function selects ‘banana’ as the value for the expression ‘y’ passed despite of having two similar matches.
By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.
For more such posts related to R programming, stay tuned and till then, Happy Learning!! 🙂