R Function Parameters

Parameters let you pass information into a function, and R adds default values, named arguments, and a catch-all ... parameter to make function calls flexible.

Parameters vs. arguments

The names listed inside a function's parentheses when you define it, like celsius in function(celsius), are called parameters; they're placeholders. The actual values you supply when you call the function, like 100 in celsius_to_fahrenheit(100), are called arguments. The distinction is small but useful: parameters describe the interface, arguments are the data flowing through it.

Example

add_tax <- function(price, rate) {
  price + price * rate
}

add_tax(200, 0.18)

Giving a parameter a default value

Default Value

power <- function(base, exponent = 2) {
  base^exponent
}

power(5)       # uses the default exponent of 2, gives 25
power(5, 3)    # overrides the default, gives 125

Adding = value after a parameter name in the function definition makes that argument optional. If the caller doesn't supply it, R uses the default; if they do, their value takes over. This is a common way to give a function sensible behavior out of the box while still allowing customization.

Calling arguments by name

Named Arguments

power(exponent = 3, base = 5)   # order doesn't matter when arguments are named
power(base = 5, 3)              # you can also mix named and positional arguments
  • Positional matching fills parameters in the order arguments are given
  • Named matching (parameter = value) lets you supply arguments in any order
  • It's common practice to pass the first argument or two positionally and use names for the rest, especially when a function has several optional parameters
  • A default value can even refer to another parameter, such as function(x, y = x * 2)

Accepting any number of extra arguments with ...

Variable-Length Arguments

add_all <- function(...) {
  values <- c(...)
  sum(values)
}

add_all(1, 2, 3)
add_all(10, 20, 30, 40)
Note: The ... parameter is how many built-in R functions, such as paste() and sum(), accept a flexible number of inputs. Inside your own function, you can collect those extra values into a vector with c(...) or forward them straight to another function that also accepts ....