Recall & Review
beginner
What is a switch statement in R?
A switch statement in R lets you choose one action from many based on a value. It helps run different code depending on the input.
Click to reveal answer
beginner
How do you write a basic switch statement in R?
Use switch(value, case1 = result1, case2 = result2, ...). R checks the value and runs the matching case.
Click to reveal answer
intermediate
What happens if no case matches in a switch statement?
If no case matches, switch returns NULL or the default if provided as the last unnamed argument.
Click to reveal answer
intermediate
Can switch in R use numeric values as cases?
Yes, switch can use numeric values. When the first argument is numeric, it picks the case by position number.
Click to reveal answer
beginner
Example: What does switch('b', a = 1, b = 2, c = 3) return?
It returns 2 because the value 'b' matches the case named 'b'.
Click to reveal answer
In R, what does switch(2, 'apple', 'banana', 'cherry') return?
✗ Incorrect
When the first argument is numeric, switch returns the case at that position. Position 2 is 'banana'.
What does switch('x', a = 1, b = 2) return if 'x' is not a case?
✗ Incorrect
If no case matches and no default is given, switch returns NULL.
Which of these is the correct way to add a default case in switch?
✗ Incorrect
The last unnamed argument acts as the default if no named case matches.
If you want to select the third case by position, what should the first argument be?
✗ Incorrect
When the first argument is numeric, switch picks the case by position number.
What type of values can the first argument of switch be?
✗ Incorrect
The first argument can be numeric (to pick by position) or character (to pick by name).
Explain how the switch statement works in R and how it differs when the first argument is numeric versus character.
Think about how you pick an option from a list by number or by name.
You got /4 concepts.
Describe how to provide a default case in an R switch statement and what happens if no case matches and no default is given.
What happens if you ask for a flavor not on the menu?
You got /3 concepts.