The “case_when” Function in R

  • Package: dplyr

  • Purpose: To create conditional transformations based on multiple conditions.

  • General Class: Data Manipulation

  • Required Argument(s):

    • None. (The main arguments are the conditions and transformations specified within the function.)

  • 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, 4),
    value = c(10, 15, 20, 25)
    )

    # Create a new column 'category' based on conditions
    result <- data %>%
    mutate(category = case_when(
    value < 10 ~ "Low",
    value >= 10 & value < 20 ~ "Medium",
    value >= 20 ~ "High"
    ))

    # Display the result
    print(result)

  • In this example, the case_when function from the dplyr package is used to create a new column ‘category’ based on multiple conditions applied to the ‘value’ column in the sample data frame data. Depending on the value of ‘value’, the corresponding category (“Low”, “Medium”, or “High”) is assigned to each row. The result is a new data frame result containing the original data along with the newly created ‘category’ column.

Previous
Previous

The “count” Function in R

Next
Next

The “across” Function in R