Default argument uses = in function definition [OK]
Hint: Use = to assign default values in function arguments [OK]
Common Mistakes:
Using <- or : instead of = for default values
Using == which is a comparison, not assignment
Placing default outside function parentheses
3. What is the output of this R code?
add <- function(a, b = 5) {
return(a + b)
}
add(3)
medium
A. 8
B. 3
C. Error: argument 'b' missing
D. 5
Solution
Step 1: Identify default argument usage
The function add has b defaulting to 5 if not provided.
Step 2: Call function with only a=3
Since b is missing, it uses default 5, so result is 3 + 5 = 8.
Final Answer:
8 -> Option A
Quick Check:
3 + default 5 = 8 [OK]
Hint: If argument missing, default value is used [OK]
Common Mistakes:
Expecting error for missing argument
Ignoring default and using only provided argument
Confusing output with just the first argument
4. Consider this R function:
multiply <- function(x, y = 2) {
x * y
}
multiply(4, )
What is the problem with this code?
medium
A. Function returns 8 because y defaults to 2.
B. Function throws error because x is missing.
C. Function ignores y and multiplies by 1.
D. Syntax error due to trailing comma without value.
Solution
Step 1: Analyze function call syntax
The call multiply(4, ) has a comma but no second argument value, which is invalid syntax in R.
Step 2: Understand R argument rules
Trailing commas without values cause syntax errors; you must omit the comma if skipping optional arguments.
Final Answer:
Syntax error due to trailing comma without value. -> Option D
Quick Check:
Trailing comma without value causes syntax error [OK]
Hint: No trailing commas without values in function calls [OK]
Common Mistakes:
Assuming default used despite syntax error
Thinking function returns result ignoring syntax
Confusing missing argument with missing value
5. You want to write an R function greet that prints a greeting message. It should take a name argument with default "Guest" and a punctuation argument with default "!". Which function definition correctly implements this?
Defaults must be assigned inside the function definition using = and quoted strings for text.
Step 2: Validate each option
greet <- function(name = "Guest", punctuation = "!") { paste0("Hello, ", name, punctuation) } correctly sets defaults with quotes and uses them in paste0. Other options misuse default assignment by placing it inside the function body, omitting defaults for optional arguments, or lacking quotes around strings (e.g., name = Guest, punctuation = !).