The “mutate_all” Function in R

  • Package: dplyr

  • Purpose: To apply a transformation to all columns in a data frame and create new columns with the results.

  • General Class: Data Manipulation

  • Required Argument(s):

    • data: The data frame to mutate.

    • list(): A list of functions to apply to each column.

  • Notable Optional Arguments:

    • None.

  • Example (with Explanation):

  • # Load necessary packages
    library(dplyr)

    # Create a sample data frame
    data <- data.frame(
    ID = c(1, 2, 3),
    value1 = c(10, 15, 20),
    value2 = c(25, 30, 35)
    )

    # Create a multiplication function
    Mult_by_2 <- function(x,y=2){return(x*y)}

    # Mutate all columns by doubling their values
    mutated_data <- data %>%
    mutate_all(list(Mult = Mult_by_2))

    # Display the mutated data,
    # In this situation "mutate_at" would be better.
    print(mutated_data)

  • In this example, the mutate_all function from the dplyr package is used to apply a transformation to all columns in the sample data frame data. The Mult_by_2 function doubles the values in each column. The result, mutated_data, contains the original columns along with new columns where the values are doubled.

Previous
Previous

The “select_if” Function in R

Next
Next

The “filter_all” Function in R