0
0
R-programmingHow-ToBeginner · 3 min read

How to Use Default Arguments in R: Simple Guide

In R, you set default arguments by assigning a value to a function parameter in the form param = value. When calling the function, if you omit that argument, R uses the default value automatically.
📐

Syntax

To create a default argument in R, assign a value to a parameter inside the function definition. This value is used if the caller does not provide that argument.

Example parts:

  • function_name <- function(param1 = default_value) { ... }
  • param1 is the argument name.
  • default_value is the value used if no argument is passed.
r
my_function <- function(x = 10) {
  return(x * 2)
}
💻

Example

This example shows a function with a default argument. Calling it without an argument uses the default. Calling it with an argument uses the given value.

r
multiply_by_two <- function(number = 5) {
  return(number * 2)
}

# Using default argument
result1 <- multiply_by_two()

# Providing argument
result2 <- multiply_by_two(10)

print(result1)
print(result2)
Output
[1] 10 [1] 20
⚠️

Common Pitfalls

One common mistake is placing arguments without defaults after those with defaults, which causes an error. Another is forgetting that default values are evaluated when the function is called, so using expressions as defaults can have unexpected results.

Also, avoid using mutable objects like lists as default arguments if you plan to modify them inside the function, as changes persist between calls.

r
wrong_function <- function(x, y = 5, z) {
  return(x + y + z)
}

# This will cause an error because z has no default but comes after y with default

correct_function <- function(x, z, y = 5) {
  return(x + y + z)
}
📊

Quick Reference

ConceptDescriptionExample
Default argumentAssign a value in function definitionfunction(x = 10) { x * 2 }
Omitting argumentUses default valuefunc() uses x=10 if default set
Providing argumentOverrides defaultfunc(5) uses x=5
Order of argsNon-defaults before defaults recommendedfunction(x, y = 2) {...}
Mutable defaultsAvoid mutable objects as defaultsUse NULL and initialize inside function

Key Takeaways

Set default arguments by assigning values in the function definition.
If you omit an argument when calling, R uses the default value automatically.
Place arguments without defaults before those with defaults for clarity.
Avoid mutable objects as default arguments to prevent unexpected behavior.
Default values are evaluated at call time, so use simple values or expressions carefully.