The “map2” Function in R
Package: purrr
Purpose: Apply a function to corresponding elements of two lists or vectors and return a list of the results.
General class: Function
Required argument(s):
.x: The first list or vector.
.y: The second list or vector.
.f: A function to apply to pairs of elements from .x and .y.
Notable optional arguments:
.progress: A logical or function to show progress, useful for long computations.
Example:
# Load the required library
library(purrr)
# Define two lists of numeric vectors
list_a <- list(c(1, 2, 3), c(4, 5, 6), c(7, 8, 9))
list_b <- list(c(10, 20, 30), c(40, 50, 60), c(70, 80, 90))
# Define a function to add corresponding elements
add_elements <- function(x, y) {x + y}
# Apply the function to pairs of vectors from the lists
results <- map2(list_a, list_b, add_elements)
# Print the results
print(results)
In this example, map2 from the purrr package is used to apply add_elements to pairs of vectors from list_a and list_b. The add_elements function adds corresponding elements from each pair of vectors. The result is a list of vectors, where each vector contains the sums of corresponding elements from the input lists.