mapply function in R

The mapply() function is a multivariate apply of sorts which applies a function in parallel over a set of arguments. lapply()iterate over a single R object but What if you want to iterate over multiple R objects in parallel then mapply() is the function for you. mapply gives us a way to call a non-vectorized function in a vectorized way. It 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.

Get the help file by typing ?mapply in your R console. To get the list of arguments it takes just type str(mapply).

 

?mapply
str(mapply)

Output:

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

  1. FUN is a function to apply
  2. … contains R objects to apply over
  3. MoreArgs is a list of other arguments to FUN.
  4. SIMPLIFY indicates whether the result should be simplified

Check the following code to understand why we need mapply function.

 

 

list(rep(1, 5), rep(2, 4), rep(3, 3), rep(4, 2), rep(5,1))

Output:

[[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

You can see that the same function (rep) is being called repeatedly where the first argument varies from 1 to 5, and the second argument varies from 5 to 1. Instead, you can use mapply:

 

mapply(rep, 1:5, 5:1)

Output:

[[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

This passes the sequence 1:4 to the first argument of rep() and the sequence 4:1 to the second argument.

Example 2:

 

set.seed(1)

noise <- function(n, mean, std) {
rnorm(n, mean, std)
}
noise(5, 1, 2) #Simulate 5 randon numbers
noise(1:5, 1:5, 2) #This only simulates 1 set of numbers, not 5

Output:

> noise(5, 1, 2)
[1] -0.2529076 1.3672866 -0.6712572 4.1905616 1.6590155
> noise(1:5, 1:5, 2)
[1] -0.6409368 2.9748581 4.4766494 5.1515627 4.3892232

Here you can use mapply() to pass the sequence 1:5 separately to the noise() function so that wecan get 5 sets of random numbers, each with a different length and mean.

 

set.seed(1)

mapply(noise, 1:5, 1:5, 2)

Output:

[[1]]
[1] -0.2529076

[[2]]
[1] 2.3672866 0.3287428

[[3]]
[1] 6.190562 3.659016 1.359063

[[4]]
[1] 4.974858 5.476649 5.151563 3.389223

[[5]]
[1] 8.0235623 5.7796865 3.7575188 0.5706002 7.2498618

If you are not eager to call the above mapply()then you need to write the following code to get the same result.

list(noise(1, 1, 2), noise(2, 2, 2), noise(3, 3, 2),noise(4, 4, 2), noise(5, 5, 2))

 

apply

Functions