Using a switch function in place of nested if functions

Viewed 31

I'm new to R and I've been studying nested if functions. I did the following exercise from The Book of R to determine precise dosages for a drug. If there was any instance of "High" in doselevel I performed operations on the various doses lowdose,meddose,highdose and returned a vector of the proper dosage. I have it working using nested if functions but it i've seen it alluded to that this is a situation that might be better suited for a switch function.

What would the switch function for this situation look like?

lowdose <- 12.5
meddose <- 25.3
highdose <- 58.1
doselevel <- factor(c("Low","High","High","High","Low","Med","Med"),levels=c("Low","Med","High"))

if(any(doselevel=="High")){
  if(lowdose>=10){
    lowdose <- 10
  } else {
    lowdose <- lowdose / 2
  }
  if(meddose>=26){
    meddose <- 26
  }
  if(highdose>=60){
    highdose <- highdose * 1.5
  } else {
    highdose <- 60
  }
  doseage <- rep(lowdose,times=length(doselevel))
  doseage[which(doselevel=="Med")] <- meddose
  doseage[which(doselevel=="High")] <- highdose
} else {
  doselevel <- factor(doselevel,c("Low","Med"),labels=c("Small","Large"))
  if((lowdose<15)&&(meddose<35)){
      lowdose <- lowdose * 1.5
      meddose <- meddose + highdose
  }
}

1 Answers

Package kit on CRAN has a nested if function called nif, it also has a vectorised switch function vswitch which is faster. For your information it also has a fast ifelse function called iif. These functions are all written in C for speed. Please look at the documentation of these functions.

Related