I have a simple question on adding a Flag to indicate if the day is out of the scheduled range. As shown in the following image, each should be occurred within a 6 day range, e.g., for Week 2, the should be 9 <= STDTY <= 21, otherwise it will be flagged as Flag="Y".
if (data$VISIT=="Screening" & data$STDTY>=-1) {
data$Flag="Y"
} else if (data$VISIT=="Day 1" & data$STDTY!=1) {
sv_domain$Flag="Y"
} else if (data$VISIT=="Week 2" & data$STDTY<(2*7 1-6)) {
data$Flag="Y"
} else if (data$VISIT=="Week 2" & data$STDTY>(2*7 1 6)) {
data$Flag="Y"
.......
I know it doesn't work, please help me out, thanks!
CodePudding user response:
if/else
is not vectorized. We may use ifelse
or more easily with case_when
library(dplyr)
case_when(data$VISIT=="Screening" & data$STDTY>=-1|
data$VISIT=="Week 2" & data$STDTY<(2*7 1-6)|
data$VISIT=="Week 2" & data$STDTY>(2*7 1 6) ~ "Y")
Or with ifelse
ifelse(data$VISIT=="Screening" & data$STDTY>=-1|
data$VISIT=="Week 2" & data$STDTY<(2*7 1-6)|
data$VISIT=="Week 2" & data$STDTY>(2*7 1 6), "Y", NA)