Learn R Programming

base (version 3.6.0)

mapply: Apply a Function to Multiple List or Vector Arguments

Description

mapply is a multivariate version of sapply. mapply applies FUN to the first elements of each … argument, the second elements, the third elements, and so on. Arguments are recycled if necessary.

Usage

mapply(FUN, …, MoreArgs = NULL, SIMPLIFY = TRUE,
       USE.NAMES = TRUE)

Arguments

FUN

function to apply, found via match.fun.

…

arguments to vectorize over (vectors or lists of strictly positive length, or all of zero length). See also ‘Details’.

MoreArgs

a list of other arguments to FUN.

SIMPLIFY

logical or character string; attempt to reduce the result to a vector, matrix or higher dimensional array; see the simplify argument of sapply.

USE.NAMES

logical; use names if the first … argument has names, or if it is a character vector, use that character vector as the names.

Value

A list, or for SIMPLIFY = TRUE, a vector, array or list.

Details

mapply calls FUN for the values of … (re-cycled to the length of the longest, unless any have length zero), followed by the arguments given in MoreArgs. The arguments in the call will be named if … or MoreArgs are named.

Arguments with classes in … will be accepted, and their subsetting and length methods will be used.

See Also

sapply, after which mapply() is modelled.

outer, which applies a vectorized function to all combinations of two arguments.

Examples

Run this code
# NOT RUN {
mapply(rep, 1:4, 4:1)

mapply(rep, times = 1:4, x = 4:1)

mapply(rep, times = 1:4, MoreArgs = list(x = 42))

mapply(function(x, y) seq_len(x) + y,
       c(a =  1, b = 2, c = 3),  # names from first
       c(A = 10, B = 0, C = -10))

word <- function(C, k) paste(rep.int(C, k), collapse = "")
utils::str(mapply(word, LETTERS[1:6], 6:1, SIMPLIFY = FALSE))
# }

Run the code above in your browser using DataLab