I want to change the values in a column based on another column.
If terminate_dyad 0 or NA then type.of.termination must be 0. If terminate_dyad 1 then type.of.termination must keep the value it has.
I tried to do that with case_when
like that:
df %>%
mutate(type.of.termination = case_when(terminate_dyad == 0 ~ 0))
However, I couldn't figure out to change NA to 0, and keep to values if terminate_dyad == 1.
Thank you in advance.
CodePudding user response:
One possible solution:
library(dplyr)
df %>%
mutate(type.of.termination = replace(type.of.termination, terminate_dyad %in% c(0, NA), 0))
# or
df %>%
mutate(type.of.termination = ifelse(terminate_dyad %in% c(0, NA), 0, type.of.termination))
CodePudding user response:
Edit to try to return what OP is asking for:
df %>%
mutate(type.of.termination = case_when(is.na(terminate_dyad) ~ 0,
terminate_dyad == 0 ~ 0,
TRUE ~ type.of.termination))
# A tibble: 15 × 3
dyadid terminate_dyad type.of.termination
<dbl> <dbl> <dbl>
1 1 0 0
2 3 0 0
3 3 0 0
4 3 0 0
5 3 0 0
6 3 0 0
7 4 0 0
8 4 0 0
9 4 0 0
10 7 1 NA
11 7 0 0
12 7 0 0
13 7 1 NA
14 11 1 1
15 12 1 6.1