0
0
R Programmingprogramming~10 mins

Default argument values in R Programming - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Default argument values
Function call
Check arguments
Argument provided?
YesUse provided value
No
Use default value
Run function body with arguments
Return result
When a function is called, R checks if each argument is given. If not, it uses the default value set in the function definition.
Execution Sample
R Programming
add <- function(x, y = 5) {
  return(x + y)
}
add(3)
add(3, 2)
Defines a function with a default value for y, then calls it with and without y.
Execution Table
StepFunction CallArgument xArgument yUsed y ValueCalculationOutput
1add(3)3missing5 (default)3 + 58
2add(3, 2)322 (provided)3 + 25
3End----Function calls complete
💡 No more function calls to execute
Variable Tracker
VariableStartCall 1Call 2Final
xundefined333
yundefined5 (default)2 (provided)2 (last call)
resultundefined855
Key Moments - 2 Insights
Why does y use 5 in the first call but 2 in the second?
Because in the first call (row 1), y is not provided, so the default 5 is used. In the second call (row 2), y is given as 2, so that value is used instead.
What happens if no default is set and argument is missing?
R will give an error because it expects that argument to be provided. Here, y has a default, so no error occurs.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output of add(3)?
A5
B8
C3
DError
💡 Hint
Check row 1 in the execution_table where add(3) is called and output is shown.
At which step does the function use the default value for y?
AStep 3
BStep 2
CStep 1
DNever
💡 Hint
Look at the 'Used y Value' column in the execution_table for each step.
If we call add(4, 10), what would be the output?
A14
B9
C5
DError
💡 Hint
Add x and y values; y is provided, so default is ignored.
Concept Snapshot
Function arguments can have default values.
If argument is missing in call, default is used.
If argument is provided, that value is used.
Helps avoid errors and simplify calls.
Syntax: function(arg = default) { ... }
Full Transcript
This example shows how R functions use default argument values. When calling add(3), y is missing, so default 5 is used, resulting in 8. When calling add(3, 2), y is provided as 2, so output is 5. The flow checks if arguments are given; if not, defaults apply. This prevents errors and makes functions flexible.