Elif Y
Elif Y

Reputation: 251

How to write multiple if/else if conditions in R on Row record selection

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!

enter image description here

Upvotes: 1

Views: 100

Answers (1)

akrun
akrun

Reputation: 887901

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)

Upvotes: 1

Related Questions