mutate() with case_when() and replace()

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! :cowboy_hat_face:

I would use ifelse since there is only one condition to check.

df <- data.frame(var1 = c(100, 200, 300, 400, 500, 600), 
                 var_condition = c(1, 1, 1, 0, 0, 0))
library(dplyr)
df <- df %>% mutate(var2 = ifelse(var_condition == 0, var1 + 600, var1))

I keep mixing up when to use case_when and when to use ifelse! Thank you for this nice and quick solution!

case_when will work, it is just a preference to use ifelse in the simplest case. I hope I don't make any silly mistakes writing code without testing it.

df <- df %>% mutate(var2 = case_when(
                    var_condition == 0 ~  var1 + 600, 
                    TRUE ~ var1)
                   )

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.