I am trying to create a new variable using mutate() but under two conditions of case_when() and replace().
My data frame looks like this:
df <- data.frame(var1 <- c(100, 200, 300, 400, 500, 600), var_condition <- c(1, 1, 1, 0, 0, 0))
The mutate function by itself is quite simple:
df %>% mutate(var2 = var1 + 600)
Ideally I would like to create the new variable var2 which uses this mutate function but only when:
case_when(!var_condition %in% c(0))
I first tried to do it with the filter() function like this
df %>% filter(!var_condition %in% c(1)) %>% mutate(var1_600 = var1 + 600)
but this deletes all the cases where var_condition = 1, so I dropped the filter() function altogether.
Instead I was trying to find a way to include case_when() AND replace() into the mutate function but couldn't make it work properly. In detail this means that I would like to replace the cases where my var_condition = 0 with the newly calculated value (var1 + 600) without dropping the cases where var_condition = 1.
The result should be this dataframe:
df2 <- data.frame(var1 <- c(100, 200, 300, 400, 500, 600), var_condition <- c(1, 1, 1, 0, 0, 0), var2 = 100, 200, 300, 1000, 1100, 1200)).
I hope that somebody can help me with this!