The “map_at” Function in R

  • Package: purrr

  • Purpose: Apply a function to specified elements or positions within a list or vector.

  • General class: Function

  • Required argument(s):

    • .x: The list or vector to be processed.

    • .at: The positions or indices of elements to which the function should be applied.

    • .f: The function to apply to the specified elements.

  • Notable optional arguments:

    • .else: A function or value to apply to elements that are not specified. If not specified, elements that are not selected remain unchanged.

    • .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_data <- list(c(1, 2, 3), c(4, 5, 6), c(7, 8, 9))

    # Define a function to add 10
    add_10 <- function(x) {x + 10}

    # Apply the function only to the first and third elements in the list
    results <- map_at(list_data, c(1, 3), add_10)

    # Print the results
    print(results)

  • In this example, map_at from the purrr package is used to apply add_10 to the first and third elements in list_data. The result is a list where only the specified elements (positions 1 and 3) are modified by the add_10 function, while the other elements remain unchanged.

Previous
Previous

The “imap” Function in R

Next
Next

The “map2” Function in R