-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbest.R
90 lines (64 loc) · 1.85 KB
/
best.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
checkTarget <- function(outcome)
{
val <- 0
if(outcome == "heart attack")
{
val <- 1
}
else if(outcome == "heart failure")
{
val <- 2
}
else if (outcome == "pneumonia")
{
val <- 3
}
val
}
## Finding the best hospital in a state
best <- function(state, outcome)
{
## read in data as "character" type from outcome-of-care-measures.csv
filename <- "outcome-of-care-measures.csv"
myData <- read.csv(filename, colClasses = "character")
## Check that state (user input) is valid
myState <- unique(myData$State)
if (!any(myState == state))
{
## typo error
stop("invalid state")
}
## Check that outcome (user input) is valid
targetlist <- c("heart attack", "heart failure", "pneumonia")
if (!any(targetlist == outcome))
{
stop("invalid outcome")
}
## find the target mortality rate from outcome
stopVal <- checkTarget(outcome)
if (stopVal == 1)
{
targetName <- "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack"
}
else if (stopVal == 2)
{
targetName <- "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Failure"
}
else if (stopVal == 3)
{
targetName <- "Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia"
}
good <- myData$State == state
## coerce the data on "outcome" column to be numeric type
myData[,targetName] <- as.numeric(myData[, targetName], na.rm=TRUE)
## Return hospital name in that state with lowest 30-day death
outData <- myData[good, c("State", targetName, "Hospital.Name")]
outData <- na.omit(outData) ## In effect the same as: outData[complete.cases(outData), ]
## find the hospital with the lowest rate
bestNum <- min(outData[targetName])
criteria <- outData[targetName] == bestNum
bestHospital <- outData[criteria, "Hospital.Name"]
## Handling ties: sort the hospital names in alphabetical order
sort(bestHospital)
bestHospital[1]
}