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 toFUN.MoreArgs: A list of other arguments toFUNthat 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
mapplyto always return a list; it simplifies output by default. - Not using
MoreArgsto 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
| Parameter | Description |
|---|---|
| FUN | Function to apply to each set of arguments |
| ... | Vectors or lists to pass as arguments to FUN |
| MoreArgs | List of additional constant arguments to FUN |
| SIMPLIFY | Whether to simplify output to vector/array (default TRUE) |
| USE.NAMES | Whether 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.