Sunday, 26 July 2015

R: mapply function

“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.

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

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.
Lets see simple example with repeating numbers.
> rep(1,5)
[1] 1 1 1 1 1
> rep(2,4)
[1] 2 2 2 2
> rep(3,3)
[1] 3 3 3
> rep(4,2)
[1] 4 4
> rep(5,1)
[1] 5

rep(1,5) repeats 1 5 times
rep(2,4) repeats 2 4 times
Above code snippet can be rewritten by using mapply like following.

> mapply(rep, 1:5, 5:1)
[[1]]
[1] 1 1 1 1 1

[[2]]
[1] 2 2 2 2

[[3]]
[1] 3 3 3

[[4]]
[1] 4 4

[[5]]
[1] 5



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment