๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

R Function Arguments

Function arguments are the values a caller passes to a function for its work. Each value fills one input from the function definition.

Several arguments in order

This function takes two arguments in a fixed order. The call passes 3 and then 4 and the sum prints.

add <- function(a, b) {
  a + b
}
print(add(3, 4))

A default value fills the gap

The second argument has a default value of Hello. The first call uses the default and the second call passes its own greeting.

greet <- function(name, greeting = "Hello") {
  print(paste(greeting, name))
}
greet("Ana")
greet("Ana", "Hi")

Naming values at the call

Each value in these calls carries its argument name. Both orders give the same greeting.

greet <- function(name, greeting) {
  print(paste(greeting, name))
}
greet(name = "Ana", greeting = "Hi")
greet(greeting = "Hi", name = "Ana")

Example

build_tag <- function(first, last, prefix = "Ms.") {
  print(paste(prefix, first, last))
}
build_tag("Ana", "Lee")
build_tag("Ana", "Lee", "Dr.")

Key points

  • A definition can list several arguments in a fixed order.
  • A call passes its values in the order the definition lists.
  • An argument can have a default value in the definition.
  • The default value is used when the caller leaves that argument out.
  • A call can attach the argument name to each value it passes.
  • Named values in a call can come in any order.

In this example, build_tag takes a first name and a last name and a prefix with a default value. The first call leaves the prefix out and the default is used.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does naming the values in a call allow?