The “mapply” Function in R

  • Package: Base R (no specific package required)

  • Purpose: Applies a function to multiple lists or vectors, taking one element from each input list at a time.

  • General Class: Functional Programming

  • Required Argument(s):

    • FUN: The function to apply.

    • ...: One or more lists or vectors (arguments to FUN).

  • Notable Optional Arguments:

    • MoreArgs: A list of additional arguments to pass to FUN.

    • SIMPLIFY: Logical; if TRUE, attempt to simplify the result.

  • Example:

  • # Example data for using the mapply function
    values1 <- c(1, 2, 3)
    values2 <- c(4, 5, 6)

    # Use mapply to apply the sum function to corresponding elements of the two vectors
    result <- mapply(FUN = sum, values1, values2)

    # Display the result
    print(result)

  • In this example, the mapply function is used to apply the sum function to corresponding elements of the values1 and values2 vectors. The resulting result vector contains the sums of the corresponding elements. The mapply function is useful when you want to apply a function to multiple input vectors or lists, element-wise.

Previous
Previous

The “replicate” Function in R

Next
Next

The “do.call” Function in R