The mapply() function in R can be used to apply a function to multiple list or vector arguments.
This function uses the following basic syntax:
mapply(FUN, …, MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE)
where:
- FUN: The function to apply
- …: Arguments to vectorize over
- MoreArgs: A list of other arguments to FUN
- SIMPLIFY: Whether or not to reduce the result to a vector.
- USE.NAMES: Whether or not to use names if the first … argument has names
The following examples show how to use this function in different scenarios.
Example 1 : Use mapply() to Create a Matrix
The following code shows how to use mapply() to create a matrix by repeating the values c(1, 2, 3) each 5 times:
#create matrix
mapply(rep, 1:3, times=5)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 2 3
[3,] 1 2 3
[4,] 1 2 3
[5,] 1 2 3
Notice how this is much more efficient than typing out the following:
#create same matrix as previous example
matrix(c(rep(1, 5), rep(2, 5), rep(3, 5)), ncol=3)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 2 3
[3,] 1 2 3
[4,] 1 2 3
[5,] 1 2 3
Example 2: Use mapply() to Find Max Value of Corresponding Elements in Vectors
The following code shows how to use mapply() to find the max value for corresponding elements in two vectors:
#create two vectors
vector1
#find max value of each corresponding elements in vectors
mapply(max, vector1, vector2)
[1] 2 4 3 4 10
Here’s how to interpret the output:
- The max value of the elements in position 1 of either vector is 2.
- The max value of the elements in position 2 of either vector is 4.
- The max value of the elements in position 3 of either vector is 3.
And so on.
Example 3: Use mapply() to Multiply Corresponding Elements in Vectors
The following code shows how to use mapply() to find multiply the corresponding elements in several vectors:
#create three vectors vec1 #find max value of each corresponding elements in vectors mapply(function(val1, val2, val3) val1*val2*val3, vec1, vec2, vec3) [1] 6 48 162 384
Here’s how to interpret the output:
- The product of the elements in position 1 of each vector is 1 * 2 * 3 = 6.
- The product of the elements in position 2 of each vector is 2 * 4 * 6 = 48.
- The product of the elements in position 3 of each vector is 3 * 6 * 9 = 162.
- The product of the elements in position 4 of each vector is 4 * 8 * 12 = 384.
Additional Resources
The following tutorials explain how to perform other common operations in R:
lapply vs. sapply in R: What’s the Difference?
How to Apply Function to Each Row in Matrix or Data Frame in R