I'm working with a data frame "mydata" containing a variable "therapy" which is a factor (0/1). Another variable is "died" (1 if died, 0 if survived). There are no missing values, so every observation has a value for therapy and died.
Now I would like to alter the value of "therapy" based on the value of "died": If died == 1, the therapy should be set to 0 (so I want do replace the existing value), otherwise the value should stay unchanged.
mydata$therapy <- ifelse(mydata$died == 1,
0,
mydata$therapy)
As a result I get values that not only contain 0 and 1, but also 2 (therapy never contained any "2"). I assume that the increment by one is due to the factor type of "therapy". Also the following code with case_when leads to the same results:
mydata <- mydata %>%
mutate(therapy = case_when(
died == 1 ~ 0,
TRUE ~ therapy))
Does anybody have an idea, what I do wrong? Or does anybody have a solutation for just changing "treatment" to zero if died == 1
and keeping all values as they are if died == 0
.