'Changing a value in a dataframe cell based on the value of another cell in that row (R)

Let's say I have a data frame

Name | Cat_1 | Val 2
---------------------
A    | red   | 0
---------------------
B    | blue  | 1
---------------------
C    | green | 2
---------------------

I want to change the value of the Val 2 column for the row that meets a given condition in a different cell.

For example, how would I change the Val_2 value for a row to 10 if its Cat_1 is equal to "blue"? I don't want to use an if statement or for loop, I feel like there is a way to get this using dplyr or something (I am using R FYI). Let me know if you can help! Thank you!



Solution 1:[1]

You may try case_when:

library(dplyr)

df %>%
  mutate(Val_2 = 
     case_when(
       Cat_1 == ”blue” ~ 10,
       Cat_1 == ”green” ~ 5,
       Cat_1 == ”red” ~ 3)
    )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anoushiravan R