0
0
R Programmingprogramming~5 mins

Switch statement in R Programming - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A'banana'
B'apple'
C'cherry'
DNULL
What does switch('x', a = 1, b = 2) return if 'x' is not a case?
ANULL
B2
C1
DError
Which of these is the correct way to add a default case in switch?
Aswitch(x, a=1, b=2, default=3)
Bswitch(x, a=1, b=2, 3)
Cswitch(x, a=1, b=2, else=3)
Dswitch(x, a=1, b=2, default())
If you want to select the third case by position, what should the first argument be?
ANULL
B'3'
C'c'
D3
What type of values can the first argument of switch be?
AOnly numeric
BOnly character strings
CEither numeric or character
DOnly logical
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.