Concept Flow - Switch statement
Start
Evaluate expression
Match case?
No→Default case if exists
Yes
Execute matched case
End
The switch statement evaluates an expression, matches it to a case, executes that case, or the default if no match.
x <- "b" switch(x, a = "Apple", b = "Banana", c = "Cherry", "Unknown fruit")
| Step | Expression Value | Case Checked | Match? | Action | Output |
|---|---|---|---|---|---|
| 1 | "b" | a | No | Check next case | |
| 2 | "b" | b | Yes | Return "Banana" | Banana |
| 3 | N/A | Stop | N/A | Exit switch | Banana |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| x | "b" | "b" | "b" | "b" |
switch(expression, case1 = value1, case2 = value2, ..., default) - Evaluates expression once - Matches expression to cases by name or position - Executes first matching case - Returns default if no match - Stops after first match
switch() function in R primarily do?switch()switch() function evaluates an expression and returns a value based on matching cases.switch().switch() in R?switch() uses named arguments for cases like case1 = value1.result <- switch("b", a = 10, b = 20, c = 30, 40)
print(result)switch(2, 1 = "one", 2 = "two", 3 = "three" )
1 = "one", which is invalid syntax for numeric switch.Pass the test and this pattern moves unknown