How can I apply, two (or more) replace cases, in a column based on rows from another column? For example, giving the next data frame
data <- data.frame(x1 = c(1, 2, 3, 2, 4, 1, 2, 3, 4, 2),
x2 = c(4, 36, 45, 22, 36, 1, 11, 12, 31, 22))
I want to apply 2 conditions:
- If X1 = 1 then replace its corresponding value in X2 by YES
- If X1 = 2 then replace its corresponding value in X2 by NO
- Leave all the other values unchanged, keep the original values in X2
I wanted to use the "replace" function with "case_when" for this but I did not find a solution. I used then the "mutate" option, but it replaced the values I wanted to leave untouched by NAs. (I want to use case_when or similar to optimize my script, here I just provide an example but I may need to substitute many cases and I do not want to have multiple times the "replace" function in my pipe :) )
I used the next:
data %>%
mutate(x2 = case_when(x1 %in% 1 ~ “YES”,
x1 %in% 2 ~ “NO”))
And what I obtained:
How can I solve this? Thank you in advance
S
