R newbie here. Can anyone please explain the error in this code?
rankall <- function(outcome, num = "best") {
data = read.csv("outcome-of-care-measures.csv", colClasses = "character")
hospital = read.csv("hospital-data.csv", colClasses = "character")
data.hospital = merge(data, hospital, by="Provider.Number")
valid_outcomes = c("heart attack"=11, "heart failure"=17, "pneumonia"=23)
if (!tolower(outcome) %in% names(valid_outcomes))
stop("invalid outcome")
state_wise = split(data.hospital, data.hospital$State.x)
ranked = lapply(state_wise,
function(elt) {
od = order(elt[,valid_outcomes[tolower(outcome)]], elt$Hospital.Name.x)
elt = elt[od, ]
deaths = elt[, valid_outcomes[tolower(outcome)]]
last = match("Not Available", deaths) - 1
if (num=="best") {
deaths[1]
} else if (num =="worst") {
deaths[last]
} else if (num >= 1 && num <= last) {
deaths[num]
} else {
NA
}
})
df = data.frame(unlist(ranked), names(state_wise))
names(df) = c("hospital", "state")
df
}
Function call:
rankall("heart attack", 3)
Error:
Error in if (num >= 1 && num <= last) { :
missing value where TRUE/FALSE needed