Error in writing if else statement

Hi, I am new to R programming and I just try to write simple If else statement in R but it is throwing me the below error and also warning message. I would like to know why this error as well as warning coming up. Can someone help me out please.

Error in if (Medication == "Medication Prior to Start of Visit" | Medication == :
missing value where TRUE/FALSE needed
In addition: Warning message:
In if (Medication == "Medication Prior to Start of Visit" | Medication == :
the condition has length > 1 and only the first element will be used

My code is given below:

searching_studyCM <- function(Start_date, End_Date, Medication) {
  if(Medication == "Medication Prior to Start of Visit" | Medication == "Medication after start of Visit")
  {
    No_days <- End_Date - Start_date
  } else if (is.na(Medication)) {
    
    No_days <- -1
    
  } else {
    No_days <- -1 
  }
  return(No_days)
}

Switch the first and second if tests: If an NA value is detected in the first, you'll get the first error since Medication == NA will evalutate to NA, rather than TRUE or FALSE.

also this is a sign that your input Medication is a vector rather than a single value, in which case if() will only consider the first value. something like ifelse() may be more appropriate. there are also helper functions like any() and all() for trying to evaluate whether some or all of the vector values match the condition, if something global should happen for that rather than a case by case basis of each value.
its kind of a big topic :slight_smile:

Along the same line as @nirgrahamuk, ifelse seems more appropriate, especially because you can ignore else if completely. If you are actually passing Meditation as a vector (as opposed to scalar) to the function, something like this is likely to do the job:

ifelse(Mediation %in% c("Medication Prior to Start of Visit", "Medication after start of Visit"), End_Date - Start_Date, -1)

The advantage of %in% is that it will not return NA even if Meditation contains NA, and will return FALSE in that case.

For your future posts, consider providing a reproducible example of your problem, regarding which there is a detailed guide here. And, welcome to the community! :slight_smile:

Thanks, I understood.

Ok, Got it, thanks. It works.

Thanks, I understood

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.