D. switch(expression, case1: value1, case2: value2, default: value3)
Solution
Step 1: Recall R's switch syntax
In R, switch() uses named arguments for cases like case1 = value1.
Step 2: Check each option
switch(expression, case1 = value1, case2 = value2, default = value3) matches R syntax. Options A, B, and C use syntax styles from other languages or incorrect separators.
result <- switch("b", a = 10, b = 20, c = 30, 40)
print(result)
medium
A. 10
B. 20
C. 30
D. 40
Solution
Step 1: Identify the switch expression and cases
The expression is "b". The cases are a=10, b=20, c=30, and a default 40.
Step 2: Match the expression to a case
Since the expression matches case "b", the value 20 is returned.
Final Answer:
20 -> Option B
Quick Check:
Expression "b" matches case b = 20 [OK]
Hint: Match expression string to named case [OK]
Common Mistakes:
Choosing default value instead of matching case
Confusing case names with values
Forgetting switch returns matched case value
4. Identify the error in this R switch statement:
switch(2,
1 = "one",
2 = "two",
3 = "three"
)
medium
A. Switch expression should be a string, not a number
B. Missing a default case
C. Incorrect use of commas between cases
D. Using numeric cases with = instead of unnamed cases
Solution
Step 1: Understand switch with numeric expression in R
When the expression is numeric, switch expects unnamed arguments, not named with =.
Step 2: Check the code
The code uses named cases like 1 = "one", which is invalid syntax for numeric switch.
Final Answer:
Using numeric cases with = instead of unnamed cases -> Option D
Quick Check:
Numeric switch uses unnamed cases, not named with = [OK]
Hint: Use unnamed cases for numeric switch, named for string [OK]
Common Mistakes:
Using = with numeric cases causes syntax error
Assuming default case is mandatory
Thinking switch expression must be string
5. You want to write a switch statement in R that returns "small", "medium", or "large" for numeric input 1, 2, or 3 respectively, and "unknown" for any other number. Which code correctly implements this?
Step 1: Understand switch behavior with numeric input
For numeric input matching positions 1,2,3, use unnamed positional arguments, placing "unknown" as the 4th for other small numbers.
Step 2: Analyze each option
A, C use string literals like '1' = which cause syntax error (unexpected =). D uses numeric literals 1 = which cause syntax error (unexpected =). B uses unnamed arguments, correct for numeric positional matching.
Final Answer:
switch(x, "small", "medium", "large", "unknown") -> Option C
Quick Check:
Numeric switch uses unnamed positional args [OK]
Hint: Unnamed args for numeric switch positions [OK]
Common Mistakes:
Using numeric cases with = causes syntax error
Not providing a default value for unmatched cases
Mixing numeric expression with string case names
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.