When in doubt, it always helps to start with some data and torture it into a usable form to be able to create a reproducible example, called a reprex to illuminate the problem.
There's no better place to start than mtcars
. Granted it deals with automobiles, but you can use it to create a dummy data set for your problem:
suppressPackageStartupMessages(library(dplyr))
exemplar <- mtcars %>% select(1:5)
rownames(exemplar) <- seq(1:nrow(exemplar))
exemplar <- exemplar %>%
mutate(mpg = ifelse(mpg < 20, 1, 0)) %>%
mutate(cyl = ifelse(cyl < 6, 1, 0)) %>%
mutate(disp = ifelse(disp < 200, 1, 0)) %>%
mutate(hp = ifelse(hp < 150, 1, 0)) %>%
mutate(drat = ifelse(drat < 3, 1, 0))
colnames(exemplar) <- c("Drug1","Drug2","Drug3","Drug4","Drug5")
exemplar
#> Drug1 Drug2 Drug3 Drug4 Drug5
#> 1 0 0 1 1 0
#> 2 0 0 1 1 0
#> 3 0 1 1 1 0
#> 4 0 0 0 1 0
#> 5 1 0 0 0 0
#> 6 1 0 0 1 1
#> 7 1 0 0 0 0
#> 8 0 1 1 1 0
#> 9 0 1 1 1 0
#> 10 1 0 1 1 0
#> 11 1 0 1 1 0
#> 12 1 0 0 0 0
#> 13 1 0 0 0 0
#> 14 1 0 0 0 0
#> 15 1 0 0 0 1
#> 16 1 0 0 0 0
#> 17 1 0 0 0 0
#> 18 0 1 1 1 0
#> 19 0 1 1 1 0
#> 20 0 1 1 1 0
#> 21 0 1 1 1 0
#> 22 1 0 0 0 1
#> 23 1 0 0 0 0
#> 24 1 0 0 0 0
#> 25 1 0 0 0 0
#> 26 0 1 1 1 0
#> 27 0 1 1 1 0
#> 28 0 1 1 1 0
#> 29 1 0 0 0 0
#> 30 1 0 1 0 0
#> 31 1 0 0 0 0
#> 32 0 1 1 1 0
Created on 2019-12-25 by the reprex package (v0.3.0)
I've chosen 1/0
in place of yes/no
in @FJCC's example, because there are advantages for when you need to use linear algebra, which isn't as scary as it might sound.
Given the faked exemplar
data set ,
rescue <- exemplar %>% mutate(rescue = ifelse(
Drug1 == 1 & Drug2 == 1 |
Drug2 == 1 & Drug3 == 1 |
Drug3 == 1 & Drug4 == 1 |
Drug4 == 1 & Drug5 == 1,
1,0))
rescue
#> Drug1 Drug2 Drug3 Drug4 Drug5 rescue
#> 1 0 0 1 1 0 1
#> 2 0 0 1 1 0 1
#> 3 0 1 1 1 0 1
#> 4 0 0 0 1 0 0
#> 5 1 0 0 0 0 0
#> 6 1 0 0 1 1 1
#> 7 1 0 0 0 0 0
#> 8 0 1 1 1 0 1
#> 9 0 1 1 1 0 1
#> 10 1 0 1 1 0 1
#> 11 1 0 1 1 0 1
#> 12 1 0 0 0 0 0
#> 13 1 0 0 0 0 0
#> 14 1 0 0 0 0 0
#> 15 1 0 0 0 1 0
#> 16 1 0 0 0 0 0
#> 17 1 0 0 0 0 0
#> 18 0 1 1 1 0 1
#> 19 0 1 1 1 0 1
#> 20 0 1 1 1 0 1
#> 21 0 1 1 1 0 1
#> 22 1 0 0 0 1 0
#> 23 1 0 0 0 0 0
#> 24 1 0 0 0 0 0
#> 25 1 0 0 0 0 0
#> 26 0 1 1 1 0 1
#> 27 0 1 1 1 0 1
#> 28 0 1 1 1 0 1
#> 29 1 0 0 0 0 0
#> 30 1 0 1 0 0 0
#> 31 1 0 0 0 0 0
#> 32 0 1 1 1 0 1
Created on 2019-12-25 by the reprex package (v0.3.0)
ifelse
is a logical test in a series of |
OR
operators that looks at successive pairs of the Drug_i columns to see if there is a 1 followed by a 1 in any of the pairs: 1:2, 2:3, 3:4, or 4:5.