0
0
R-programmingHow-ToBeginner · 3 min read

How to Use mapply in R: Syntax and Examples

In R, mapply applies a function to multiple arguments in parallel, recycling elements as needed. It is like Map but simplifies the output to a vector or array when possible.
📐

Syntax

The basic syntax of mapply is:

  • FUN: The function to apply.
  • ...: Multiple arguments (vectors, lists) to pass to FUN.
  • MoreArgs: A list of other arguments to FUN that stay constant.
  • SIMPLIFY: Logical, whether to simplify the result to a vector or array.
  • USE.NAMES: Logical, whether to use names from the first argument.
r
mapply(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE)
💻

Example

This example shows how mapply applies a function to two vectors element-wise, multiplying corresponding elements.

r
x <- 1:5
y <- 6:10
result <- mapply(function(a, b) a * b, x, y)
print(result)
Output
[1] 6 14 24 36 50
⚠️

Common Pitfalls

Common mistakes include:

  • Passing arguments of different lengths without understanding recycling rules.
  • Expecting mapply to always return a list; it simplifies output by default.
  • Not using MoreArgs to pass constant parameters to the function.

Here is a wrong and right way example:

r
# Wrong: forgetting to use MoreArgs for constant parameter
x <- 1:3
y <- 4:6
mapply(function(a, b, c) a + b + c, x, y, 10) # Warning, but works due to recycling

# Right: use MoreArgs for constant parameter
mapply(function(a, b, c) a + b + c, x, y, MoreArgs = list(c = 10))
Output
[1] 15 17 19
📊

Quick Reference

ParameterDescription
FUNFunction to apply to each set of arguments
...Vectors or lists to pass as arguments to FUN
MoreArgsList of additional constant arguments to FUN
SIMPLIFYWhether to simplify output to vector/array (default TRUE)
USE.NAMESWhether to use names from first argument (default TRUE)

Key Takeaways

Use mapply to apply a function element-wise to multiple arguments in parallel.
Pass constant parameters to the function using MoreArgs to avoid errors.
mapply simplifies the output by default; set SIMPLIFY = FALSE to keep a list.
Ensure input vectors have compatible lengths or understand recycling rules.
mapply is a multivariate version of sapply and Map with output simplification.