In this post, I am building on the code I wrote in a previous post where l try to find the best hospital in a state given a condition such as heart attack, heart failure or pneumonia.
The upgrade code is to find either the best or the worst for each of the state and output it for each of the states with complete data from the hospital compare website. To get the background for this post, please read the introductory post on the topic here

rankall<- function(outcome,num = "best"){
    outcomes <- c("heart attack" = "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack",
                  "heart failure" = "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Failure", 
                  "pneumonia" = "Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia")
    if(outcome %in% names(outcomes))
    {
        filedata <-read.csv("outcome-of-care-measures.csv", colClasses = "character")
        outcome <- outcomes[[outcome]]
        workdata <- filedata[ ,c("Hospital.Name", "State",outcome)] 
        workdata[,outcome] <- as.numeric(workdata[,outcome])
        good <- !is.na(workdata[outcome])
        workdata <- workdata[good,]
        if (num %in% c("best","worst") || is.numeric(num) )
        {
            states<-workdata[["State"]]
            states <- unique(states)
            hospital_vect <- vector(mode = "character", length = length(states))
            if(num == "best")
            {
                i<-1
                for( st in states)
                {
                    good <- workdata["State"] == st
                    statedata <- workdata[good, ]
                    satedata <- statedata[order(statedata[outcome],statedata["Hospital.Name"]),]
                    hospital_vect[i] <- statedata[1,"Hospital.Name"]
                    i=i+1
                }
            }
            else if(num =="worst")
            {
                i <- 1
                for( st in states)
                {
                    good <- workdata["State"] == st
                    statedata <- workdata[good, ]
                    satedata <- statedata[order(statedata[outcome],statedata["Hospital.Name"]),]
                    hospital_vect[i] <- statedata[nrow(statedata),"Hospital.Name"]
                }
            }
            output<-data.frame(states,hospital_vect,stringsAsFactors = FALSE,row.names = NULL)
            colnames(output) <- c("State","HospitalName")
            output
        }
        else
        {
            stop("Invalid input") 
        }
    }
    else
    { 
        stop('Invalid Outcome') 
    }
}

Below is a snapshot of the code run

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *