The “apply” Function in R

  • Package: Base R (no specific package required)

  • Purpose: Applies a function to the rows or columns of a matrix, or the margins of an array.

  • General Class: Data Manipulation

  • Required Argument(s):

    • X: A matrix or array.

    • MARGIN: A vector indicating which margins should be retained after applying the function.

    • FUN: The function to apply.

  • Notable Optional Arguments:

    • ...: Additional arguments passed to the function specified by FUN.

    • simplify: Logical; if TRUE, attempts to reduce the result to a simpler form.

    • USE.NAMES: Logical; if TRUE and X is a named array, the names are used to name the result.

  • Example:

  • # Example data for using the apply function
    matrix_example <- matrix(1:6, nrow = 2, ncol = 3)

    # Apply the sum function to each column of the matrix
    result <- apply(matrix_example, MARGIN = 2, FUN = sum)

    # Display the result
    print(result)

  • In this example, the apply function is used to apply the sum function to each column of the matrix_example. The resulting result vector contains the sums of the columns. The apply function is versatile and can be used to apply a function along the rows or columns of a matrix or the margins of an array.

Previous
Previous

The “tapply” Function in R

Next
Next

The “lapply” Function in R