0
0
R Programmingprogramming~10 mins

Switch statement in R Programming - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Switch statement
Start
Evaluate expression
Match case?
NoDefault 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.
Execution Sample
R Programming
x <- "b"
switch(x,
       a = "Apple",
       b = "Banana",
       c = "Cherry",
       "Unknown fruit")
This code uses switch to return a fruit name based on the value of x.
Execution Table
StepExpression ValueCase CheckedMatch?ActionOutput
1"b"aNoCheck next case
2"b"bYesReturn "Banana"Banana
3N/AStopN/AExit switchBanana
💡 Match found at case 'b', switch returns 'Banana' and stops.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
x"b""b""b""b"
Key Moments - 2 Insights
What happens if the expression value does not match any case?
If no case matches, the switch returns the default value (last unnamed argument). See execution_table exit_note for no-match scenario.
Does switch check all cases even after a match?
No, switch stops checking after the first match, as shown in execution_table step 2 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 2?
A"Cherry"
B"Banana"
C"Apple"
D"Unknown fruit"
💡 Hint
Check the 'Output' column at step 2 in the execution_table.
At which step does the switch stop checking cases?
AStep 3
BStep 1
CStep 2
DIt checks all cases
💡 Hint
Look at the 'Action' column in steps 2 and 3 in execution_table.
If x was "d", what would the output be?
A"Cherry"
B"Banana"
C"Unknown fruit"
D"Apple"
💡 Hint
Refer to key_moments about default case when no match is found.
Concept Snapshot
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
Full Transcript
The switch statement in R evaluates an expression and compares it to each case in order. When it finds a matching case, it executes that case and stops checking further cases. If no case matches, it returns the default value, which is the last unnamed argument. For example, if x is "b", switch returns "Banana" because it matches the case named "b". If x does not match any case, switch returns the default value like "Unknown fruit". This behavior helps select one value from many options based on a single expression.