The “aggregate” Function in R

  • Package: Base R (no specific package required)

  • Purpose: Applies a function to the data in each group of a data frame.

  • General Class: Data Manipulation

  • Required Argument(s):

    • x: A data frame or matrix.

    • by: A list of grouping elements, typically the grouping variables.

  • Notable Optional Arguments:

    • FUN: The function to be applied to each group. It can be a function or a formula.

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

    • simplify: A logical value indicating whether to simplify the result.

  • Example:

  • # Example data for aggregating using the aggregate function
    df <- data.frame(
    ID = c(1, 2, 3, 4, 5, 6),
    Category = c("A", "B", "A", "B", "A", "B"),
    Value = c(10, 15, 20, 25, 30, 35)
    )

    # Aggregate the sum of "Value" by "Category"
    aggregated_df <- aggregate(Value ~ Category, data = df, FUN = sum)

    # Display the aggregated data frame
    print(aggregated_df)

  • In this example, the aggregate function from base R is used to aggregate the sum of the “Value” column by the “Category” column in a data frame (df). The result is an aggregated data frame (aggregated_df).

Previous
Previous

The “cut” Function in R

Next
Next

The “group_by” Function in R