dplyr mutate with conditional values


# Assuming 'df' is your data frame and 'column_name' is the column you want to mutate
df <- df %>%
  mutate(new_column = case_when(
    condition1 ~ value1,
    condition2 ~ value2,
    condition3 ~ value3,
    TRUE ~ default_value


  1. mutate(): This function is used to add new variables to a data frame.

  2. case_when(): It allows you to specify multiple conditions and corresponding values in a concise manner.

  3. condition1, condition2, condition3: These are logical conditions that you define based on the values in your existing columns. If these conditions are met, the corresponding values will be assigned to the new column.

  4. value1, value2, value3: These are the values that will be assigned to the new column if the corresponding conditions are met.

  5. TRUE ~ default_value: This part specifies the default value to be assigned if none of the previous conditions are true.

  6. new_column: Replace this with the desired name for your new column.

Make sure to replace df with the actual name of your data frame and adjust the conditions, values, and column names according to your specific use case.