The “tapply” Function in R

  • Package: Base R (no specific package required)

  • Purpose: Applies a function to subsets of a vector or data frame broken down by one or more factors.

  • General Class: Data Manipulation

  • Required Argument(s):

    • X: A vector or data frame.

    • INDEX: A factor or a list of factors defining the subsets.

    • FUN: The function to apply.

  • Notable Optional Arguments:

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

  • Example:

  • # Example data for using the tapply function
    values <- c(1, 2, 3, 4, 5, 6)
    groups <- factor(c("A", "B", "A", "B", "A", "B"))

    # Apply the sum function to subsets based on the factor 'groups'
    result <- tapply(values, INDEX = groups, FUN = sum)

    # Display the result
    print(result)

  • In this example, the tapply function is used to apply the sum function to subsets of the values vector based on the factor groups. The resulting result vector contains the sums for each level of the factor. The tapply function is commonly used when you want to apply a function to subsets defined by factors.

Previous
Previous

The “do.call” Function in R

Next
Next

The “apply” Function in R