I am learning R and was trying to solve the Coursera Best Hospital assignment. For some reason, my function's results are inconsistent. It gives correct answers only in 4 out of 6 sample outputs. I looked through the internet and already got rid of all the warnings I had along the way. But cannot figure out the function bug. I appreciate your time and any constructive comments you can provide on how to improve the function. Thank you all very much.
best <- function (state, outcome) {
data <- read.csv("outcome-of-care-measures.csv", header = TRUE, colClasses = "character",
na.strings = "Not Available")
select_o <- if (outcome == "heart attack") {
"Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack"
} else if (outcome == "heart failure") {
"Hospital.30.Day.Death..Mortality..Rates.from.Heart.Failure"
} else if (outcome == "pneumonia") {
"Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia"
} else {
stop("invalid outcome")
}
for (i in nrow(data)) {
if(data$State[i] != state) {
stop("invalid state")}
}
best_data <- data[data$State == state, c("Hospital.Name", select_o)]
na.omit(best_data)
best_data[, select_o] <- as.numeric(best_data[, select_o])
ordered <- order(best_data[, select_o], best_data[, "Hospital.Name"])
as.character(best_data[, "Hospital.Name"][ordered[1]])
}
When I test sample outputs I get these results:
> best("TX", "heart attack")
[1] "CYPRESS FAIRBANKS MEDICAL CENTER"
correct
> best("TX", "heart failure")
[1] "FORT DUNCAN MEDICAL CENTER"
correct
> best("MD", "heart attack")
Error in best("MD", "heart attack") : invalid state
it should print " Johns Hopkins Hospital, The" here
> best("MD", "pneumonia")
Error in best("MD", "pneumonia") : invalid state
and "Greater Baltimore Medical Center" here
> best("BB", "heart attack")
Error in best("BB", "heart attack") : invalid state
correct
> best("NY", "hert attack")
Error in best("NY", "hert attack") : invalid outcome
correct