The “map” Function in R

  • Package: purrr

  • Purpose: Apply a function to each element of a list or vector and return a list of the results.

  • General class: Function

  • Required argument(s):

    • .x: A list or vector to which the function is applied.

    • .f: A function to apply to each element of .x.

  • Notable optional arguments:

    • .progress: A logical or function to show progress, useful for long computations.

  • Example:

  • # Load the required library
    library(purrr)

    # Define a list of numeric vectors
    list_of_vectors <- list(c(1, 2, 3), c(4, 5, 6), c(7, 8, 9))

    # Apply the function to each vector in the list
    results <- map(list_of_vectors, sum)

    # Print the results
    print(results)

  • In this example, the map function from the purrr package is used to apply the function “sum” to each element in list_of_vectors. The “sum” function calculates the sum of the elements in each vector. The result is a list of sums corresponding to each vector.

Previous
Previous

The “map2” Function in R

Next
Next

The “neuralnet” Function in R