Apply a Function to Elements of Multiple Inputs in Parallel

TL;DR pmap(.l, .f) is very similar to map(.x, .f) and map2(.x, .y, .f), but but applies the operation .f in parallel to elements of multiple inputs defined by the argument .l. It returns a list. The pmap_*() functions, e.g., pmap_lgl(), pmap_dbl(), pmap_int() and pmap_chr(), works in a similar way as pmap() but returns a vector of the indicated type.


The pmap() function applies an operation to each element of multiple inputs in parallel. The basic argument structure follows map(.l, .f) (as in functions of pmap_*()):

  • .l: A list of inputs (vectors, lists, etc). Arguments will be supplied by position if unnamed, and by name if named. Vectors of length 1 will be recycled to any length; all other elements must be have the same length.

  • .f defines the function to be applied to each paired elements in the input. It can be in the format of a named function (without quote), e.g. sum; or an anonymous function, e.g., ~ sum(.x, .y, .z), ~ .x + .y + .z, \(x, y, z) x + y + z, and function(x, y, z) x + y + z.

  • The output is a list of the same length as the input.

If .f returns a vector of length one in each iteration, you can return the result as a vector of the indicated type:

  • pmap_dbl() returns a vector of type of double (i.e., numeric).
  • pmap_lgl() returns a vector of type of logic.
  • pmap_int() returns a vector of type of integer.
  • pmap_chr() returns a vector of type of character.

e.g.1. Calculate A + B + C + D, and return a list.

library(purrr)library(dplyr)
A <- c(1, 2, 4)B <- c(0, 1, 2)C <- c(1, 2, 3)D <- c(1, 2, 3)
pmap(.l = list(A, B, C, D), .f = sum)

Output:

[[1]]
[1] 3
[[2]]
[1] 7
[[3]]
[1] 12
pmap_dbl(.l = list(A, B, C, D), .f = sum)

Output:

[1] 3 7 12

e.g.2. Calculate AB + CD: raise A to the power of B, and C to the power of D, and then sum up.

pmap(.l = list(A, B, C, D), .f = \(x, y, z, h) x ^ y + z ^ h )

Output:

[[1]]
[1] 2
[[2]]
[1] 6
[[3]]
[1] 43

e.g.3. The following code creates three vectors (of a list) of a normal distribution, with 3, 5, and 7 as elements number n per vector, with 1, 5, and 10 as the mean, and 0.1, 1 and 5 as the associated sd, respectively.

N <- c(3, 5, 7)  # number of elements per vectorM <- c(1, 5, 10) # mean of normal distributionS <- c(.1, 1, 5) # sd of the normal distribution
pmap( list(N, M, S), .f = \(N, M, S) rnorm(n = N, mean = M, sd = S) %>% round(2))

Output:

[[1]]
[1] 0.85 1.00 1.11
[[2]]
[1] 4.54 6.44 3.40 7.18 5.95
[[3]]
[1] 3.58 17.87 8.48 13.65 -1.08 9.83 16.18