Argument Order and Named Arguments

When you specify a function in R, you assign a name to each argument in the function. Inside the body of the function, you can access the arguments by name. For example, consider the following function definition:

> addTheLog <- function(first, second) {first + log(second)}

This function takes two arguments, called first and second. Inside the body of the function, you can refer to the arguments by these names.

When you call a function in R, you can specify the arguments in three different ways (in order of priority):

  1. Exact names. The arguments will be assigned to full names explicitly given in the argument list. Full argument names are matched first:

    > addTheLog(second=exp(4), first=1)
    [1] 5
  2. Partially matching names. The arguments will be assigned to partial names explicitly given in the arguments list:

    > addTheLog(s=exp(4), f=1)
    [1] 5
  3. Argument order. The arguments will be assigned to names in the order in which they were given:

    > addTheLog(1, exp(4))
    [1] 5

When you are using generic functions, you cannot specify the argument name of the object on which the generic function is being called. You can still specify names for other arguments.

When possible, it’s a good practice to use exact argument names. Specifying full argument names does require extra typing, but it makes your code easier to read and removes ambiguity.

Partial names are a deprecated feature because they can lead to confusion. As an example, consider the following function:

> f <- function(arg1=10, ...

Get R in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.