How to Use the mapply() Function in R (With Examples)


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 <- c(1, 2, 3, 4, 5)
vector2 <- c(2, 4, 1, 2, 10)

#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 <- c(1, 2, 3, 4)
vec2 <- c(2, 4, 6, 8)
vec3 <- c(3, 6, 9, 12)

#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

2 Replies to “How to Use the mapply() Function in R (With Examples)”

  1. mapply mainly used for parallel processing, as per my understanding. Please correct me if I am wrong.

    1. Hi Elaiyaraja…The `mapply()` function in R is actually not primarily used for parallel processing. Instead, `mapply()` is a multivariate version of the `apply()` function, which applies a function to the elements of one or more lists or vectors in a parallel manner (in the sense of applying the function to each element simultaneously, not in the sense of computational parallelism).

      ### Understanding `mapply()`

      `mapply()` is used to apply a function to multiple arguments. It simplifies the process of applying a function to multiple sets of arguments, especially when the arguments are vectors or lists.

      Here’s the basic syntax of `mapply()`:

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

      – `FUN`: The function to apply.
      – `…`: The arguments to the function `FUN`.
      – `MoreArgs`: A list of other arguments to `FUN`.
      – `SIMPLIFY`: Logical; should the result be simplified to a vector, matrix, or higher-dimensional array if possible?
      – `USE.NAMES`: Logical; should the result be named? If `TRUE` and if the arguments have names, the result will be named.

      ### Example Usage of `mapply()`

      Here’s a simple example to illustrate how `mapply()` works:

      “`r
      # Define a simple function that takes two arguments
      sum_function <- function(x, y) { x + y } # Create two vectors vector1 <- c(1, 2, 3) vector2 <- c(4, 5, 6) # Apply the function to each pair of elements from the vectors result <- mapply(sum_function, vector1, vector2) print(result) # Output: [1] 5 7 9 ``` In this example, `mapply()` applies the `sum_function` to each pair of elements from `vector1` and `vector2`. ### Comparing with `sapply()` and `apply()` - **`sapply()`**: Applies a function to each element of a list or vector and simplifies the result. - **`apply()`**: Applies a function over the margins of an array or matrix (e.g., rows or columns). - **`mapply()`**: Applies a function to multiple sets of arguments, allowing for multivariate input. ### Parallel Processing in R For actual parallel processing in R, you would use packages like `parallel`, `foreach`, `future.apply`, or others designed for parallel computation. Here’s an example using the `parallel` package: ```r library(parallel) # Define a function to be applied in parallel parallel_function <- function(x) { x^2 } # Create a cluster with 2 cores cl <- makeCluster(2) # Apply the function in parallel result <- parLapply(cl, 1:10, parallel_function) # Stop the cluster stopCluster(cl) print(result) # Output: List of squares of numbers from 1 to 10 ``` ### Summary - `mapply()` is used for applying a function to multiple arguments (vectors or lists) simultaneously. - It is not primarily used for parallel processing in the computational sense. - For parallel processing, consider using packages specifically designed for that purpose, such as `parallel`, `foreach`, or `future.apply`. I hope this clarifies the use of `mapply()`! If you have any more questions or need further examples, feel free to ask.

Leave a Reply

Your email address will not be published. Required fields are marked *