r - 在调用函数时,可以采取哪些额外的预防措施来防止不必要的引导到 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()
解决方案
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()
希望这可以帮助。
推荐阅读
- mysql - 选择好友提醒
- rubocop - Rubocop -- 仅在命令行上命名多个警察?
- python - 猴子从库中修补 python 类方法
- php - 网站有时会变慢并自行修复
- java - 如果 Java 中的超类方法已经被子类覆盖,如何访问它?
- xaml - Xamarin 绑定不适用于生成的可观察集合
- python - Google Colab - pandas/pyplot 将只接受列引用而不是标题
- scala - 如何将地图列表传递给 Gatling 中的卵石模板?
- javascript - Bootstrap 的 Javascript 在 Rails 6 webpacker 设置中不起作用
- swift - 了解 SHA1-UPDATE 和 SHA1-FINAL 函数