The “mutate” Function in R

  • Package: dplyr

  • Purpose: Adds new columns or modifies existing columns in data frames.

  • General Class: Data Manipulation

  • Required Argument(s):

    • .data: A data frame or tibble.

    • ...: Expressions that define the new columns.

  • Notable Optional Arguments:

    • None specific to mutate, but it can be used in combination with other functions from dplyr (e.g., filter, select, etc.).

  • Example:

  • # Example data for mutating a data frame using dplyr
    library(dplyr)

    df <- data.frame(
    ID = 1:5,
    Name = c("Alice", "Bob", "Charlie", "David", "Emma"),
    Age = c(25, 30, 22, 28, 35)
    )

    # Add a new column "Age_Group" based on the "Age" column
    mutated_df <- mutate(df, Age_Group = ifelse(Age > 30, "Old", "Young"))

    # Display the mutated data frame
    print(mutated_df)

  • In this example, the mutate function from the dplyr package is used to add a new column (“Age_Group”) to a data frame (df) based on a condition from an existing column (“Age”). The result is a mutated data frame (mutated_df) with the additional column. Note that you need to have the dplyr package installed and loaded to use the mutate function.

Previous
Previous

The “arrange” Function in R

Next
Next

The “aov” Function in R