Default Arguments
A default argument is a backup answer a function uses when you say nothing, like a sandwich that comes with butter unless you refuse. You only fill in what you want to change.
In this page:
Syntax
function_name <- function(arg1, arg2 = default_value) {
# body
}
Default Arguments
A parameter can have a default value specified in the function definition, making it optional at the call site. If the caller doesn't supply that argument, the default is used instead.
Default values can even reference other parameters of the same function.
Note:
Place parameters with defaults after required parameters, mirroring the convention used in most other languages.
Example: Default Arguments
greet <- function(name, greeting = "Hello") {
cat(greeting, ",", name, "!\n")
}
greet("Alice")
greet("Bob", "Welcome")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Placing default parameters before required ones, and then passing values by position by mistake.
- Writing the default with
:or==instead of=, such asgreeting == "Hello". - Assuming a default is fixed, when a default can use other arguments and is evaluated when needed.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: