首页 > 解决方案 > 在调用函数时,可以采取哪些额外的预防措施来防止不必要的引导到 if 语句中?

问题描述

在下面的代码中,当调用函数 best() 时,尽管结果参数以心脏病发作作为输入,但带有“错误条件,重试”的 if 语句被触发。为什么会出现这种情况,可以做些什么来防止这种情况发生?

best("CA","heart attack")

best <- function(state, outcome) {
     #read file function


  dataTable  <- read.csv("outcome.csv", header = TRUE)
  choice <- state
  stateOfChoice <- dataTable[which(dataTable$state == choice),]

  if(outcome != "heart failure" || outcome != "heart attack" || outcome != "pneumonia"){
    print("wrong condition, try again")
    main()
  }

  else if (outcome == "heart attack"){
    #subsetting,selecting column of "Lower mortality estimate [xxxSpecified  Outcomexxx ]"  & the Hospital name attach to it
    heart_attack <- stateOfChoice[which.min(stateOfChoice$Lower.Mortality.Estimate...Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack),]
    hospital <- heart_attack$Hospital.Name
    return(hospital)
  }

  else if (outcome == "heart failure"){
    heart_failure <- stateOfChoice[which.min(stateOfChoice$Lower.Mortality.Estimate...Hospital.30.Day.Death..Mortality..Rates.from.Heart.Failure),]
    hospital <- heart_failure$Hospital.Name
    return(hospital)
  }

  else if (outcome == "pneumonia"){
    pneumonia <- stateOfChoice[which.min(stateOfChoice$Lower.Mortality.Estimate...Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia),]
    hospital <- pneumonia$Hospital.Name
    return(hospital)
  }

}





main <- function() {
  print("Type Heart Attack, .....")

  outcome <- readline(prompt="Type your selection ")

  print("Select state")

  state <- readline(prompt ="Type in your selection")

  best(state,outcome)
}

main()

标签: r

解决方案


If 条件应该是这样的(如果你想使用你的解决方案):

if(outcome != "heart failure" && outcome != "heart attack" && outcome != "pneumonia") {
   #do stuff
}

但是,更好的方法是:

if(! outcome %in% c("heart failure", "heart attack", "pneumonia"))

或者 - 您可以按以下格式构建 if/else 语句:

if()
else if()
else if()
else if()
else if()
...
else
  print("wrong condition, try again")
  main()

希望这可以帮助。


推荐阅读