What is the do.call() Function in R

The do.call() function in R is “used to construct and execute a function call from a name or a function, as well as a list of arguments to be passed to it.”

Syntax

do.call(what, args)

Parameters

  1. what: It represents either the function or a non-empty character and names the function to be called.
  2. args: It represents the list of arguments to the function call.

Return value

The do.call() function returns the result of the (evaluated) function call.

Example 1: How to Use do.call() function in R

multiplication <- function(a, b) {
   a * b
}

# Creating the list of arguments to the function call
args <- list(c(1, 2, 3), c(2, 4, 6))


# Implementing the do.call() function
do.call(multiplication, args)

Output

[1] 2  8  18

Example 2: Complex code

We will create a function that takes two arguments, multiplies them together, and then adds a third argument. Then we’ll use do.call() to call this function with a list of arguments:

main_func <- function(x, y, z) {
  result <- (x * y) + z
  return(result)
}

# Define a list of arguments for the custom function
args <- list(x = 2, y = 3, z = 4)

# Use do.call() to call the custom function with the list of arguments
result <- do.call(main_func, args)

print(result)

Output

[1] 10

That’s it.

Leave a Comment