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.
In R programming, a switch statement is used to evaluate an expression and execute a block of code based on the value of the expression. The switch statement provides a simple way to implement multiple conditional statements with a single expression.
The syntax for a switch statement in R is as follows:
switch(expression, case1 = { statements1 }, case2 = { statements2 }, default = { statements3 } )
The switch statement takes an expression as its first argument, which is evaluated to determine which case to execute. The subsequent arguments to the switch statement are the cases, which are labeled with a name and enclosed in curly braces. The final case is the default case, which is executed if none of the other cases match the expression.
Here's an example of a switch statement in R:
x <- 2 switch(x, "one" = { print("The value is one.") }, "two" = { print("The value is two.") }, default = { print("The value is not one or two.") } )
In this example, the expression x
has a value of 2, so the second case is executed and the output is "The value is two." If x
had a value of 1, the first case would be executed and the output would be "The value is one." If x
had a value other than 1 or 2, the default case would be executed and the output would be "The value is not one or two."
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.